Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scroll to first added element #33

Closed
vellrya opened this issue Nov 30, 2020 · 7 comments
Closed

Scroll to first added element #33

vellrya opened this issue Nov 30, 2020 · 7 comments

Comments

@vellrya
Copy link

vellrya commented Nov 30, 2020

Hello, I use MVVM pattern with OneAdapter in my app. When new element added to 0 position in items list, we need to manually scroll up to see recently added element. If, for example, new element has index 1, then all work correct and there is animation of adding element.
Do you know any way to automatically scroll to top of list when new element has index 0 and old element with index 0 was visible by user before updating?
Or, probably, scroll to top of list always - it also acceptable for me)

Short code fragment to update adapter:

        dialogViewModel.allDialogs.observe(this) { dialogs ->
            oneAdapter.setItems(dialogs)
        }

Update: When elements in the list takes smaller space then available on screen, animation of adding element with 0 index works correct, but after empty space on screen left, list just stop updating even if the user is at the very beginning of the list and expects to see new items from the top.

@idanatz
Copy link
Collaborator

idanatz commented Dec 1, 2020

Hi,
I'm not sure I understand the issue.
Please specify each issue steps in details on how to recreate, expected outcome, and the actual outcome.
Attach code snippets or gifs that represent those issues.

In general, the item animations are controlled by the recycler view and the diff utils mechanisms, not the adapter.
If an item is not visible to the user the animation will not run, else it should. (again based on the diffing mechanism, not the adapter)

@vellrya
Copy link
Author

vellrya commented Dec 1, 2020

Probably video should help to understand what I wrote about)
https://dropmefiles.com/G3uhp

New element, which add to top of current elements in adapter, doesn't appear in top automatically. It's required from user to scroll up to see newly added element - it isn't user friendly, I think.

@idanatz
Copy link
Collaborator

idanatz commented Dec 2, 2020

Thanks for the video.
It's a known issue with RecyclerView and LayoutManager, just google "recyclerview notifyiteminserted not animating" and you will find dozens of questions regarding the same issue.

This is happening because LayoutManager thinks the item is inserted above the first item. This behavior makes sense when you are not at the top of the list but I agree that it is unintuitive when you are at the top of the list.

It's not the adapter's responsibility to change this behavior.

A possible solution can be found here

@vellrya
Copy link
Author

vellrya commented Dec 2, 2020

Thank you for explanation, I already found this SO answer, but unable to get acceptable result (works in 1 case of 10, probably).
If I call restoreScrollPositionAfterAdAdded right after setItems, diffUtil can't calculate new list properly at this time(?) and in method I get:

firstVisibleItemPosition: 0

but layoutManager.scrollToPosition(0) does nothing in 90% of trying and manual scrolling needed. In 10% of case recyclerView correctly scroll to new element, but this is sad statistics. Probably postDelayed handler can help, but this is a reinventing the wheel...
Another idea: some callback from oneAdapter should help call restoreScrollPosition at a right time, what do you think?
Current code:

        dialogViewModel.allDialogs.observe(this) { dialogs ->
            oneAdapter.setItems(dialogs)
            restoreScrollPositionAfterAdAdded()
        }

@idanatz
Copy link
Collaborator

idanatz commented Dec 2, 2020

I understand your issue, its indeed due to the async nature of diffUtil.
You can attach a hook to the RecyclerView to be notified when the data actually changes after the diffing is done.

I can expose a method on the adapter that will let you register a listener to be notified when the data is changing.
The method is registerAdapterDataObserver with a AdapterDataObserver instance passed as a parameter.
With it you can listen to onItemRangeInserted and if the positionStart is 0 scroll to the position.

Like this:

	oneAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
		override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

			if (firstVisibleItemPosition == 0 && positionStart == 0) {
				layoutManager.scrollToPosition(0)
			}
		}
	})

I've tested and it worked 100% of the time.

@vellrya
Copy link
Author

vellrya commented Dec 2, 2020

Great solution!

Right now it can be fixed with this code:

binding.dialogsRV.adapter?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                val layoutManager = (binding.dialogsRV.layoutManager as LinearLayoutManager?) ?: return
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                if (firstVisibleItemPosition == 0 && positionStart == 0) {
                    layoutManager.scrollToPosition(0)
                }
            }
        })

Works as expected, thank you!
I will switch to registerAdapterDataObserver method of the oneAdapter directly, when it will available)

Upd. I made some modification to handle update, when element moves to first position.
Useful for those who have the same question.

        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.dialogsRV.layoutManager = layoutManager
        binding.dialogsRV.adapter?.registerAdapterDataObserver(object :
            RecyclerView.AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                if (firstVisibleItemPosition == 0 && positionStart == 0) {
                    layoutManager.scrollToPosition(0)
                }
            }

            override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                if (firstVisibleItemPosition == 0 && toPosition == 0) {
                    layoutManager.scrollToPosition(0)
                }
                super.onItemRangeMoved(fromPosition, toPosition, itemCount)
            }
        })

@idanatz
Copy link
Collaborator

idanatz commented Jan 25, 2021

v2.0.2 is out with your request

@idanatz idanatz closed this as completed Jan 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants