Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recycler view not scrolling to the top after adding new item at the top, as changes to the list adapter has not yet occurred

I am getting the new list with new item at the start in my live data and then using its data to update the adapter

viewModel.myLiveData.observe { this, Observer { myList ->          adapter.submitList(myList)          recyclerView.scrollToPosition(0) } 
like image 498
nayan dhabarde Avatar asked Aug 17 '18 05:08

nayan dhabarde


People also ask

How do I scroll from my recycler view to the top?

In the above code we have added recycler view to window manger as relative parent layout and add FloatingActionButton. FloatingActionButton supports CoordinatorLayout. So we have used parent layout is CoordinatorLayout. When you click on FloatingActionButton, it will scroll to top position.

Is recycler view scrollable?

To help you build apps with lists, Android provides the RecyclerView . RecyclerView is designed to be very efficient, even with large lists, by reusing, or recycling, the views that have scrolled off the screen.

How do I stop refreshing RecyclerView data scroll to top position android?

Just set your LayoutManager and adapter for the first time. Make a setDataList method in your adapter class. And set your updated list to adapter list. And then every time of calling API set that list to setDataList and call adapter.


1 Answers

submitList does its work on a background thread, so there will always be race conditions that delays can't solve. Fortunately, we can use a RecyclerView.AdapterDataObserver callback to be informed when the list calculations are complete:

yourRecyclerViewAdapter.registerAdapterDataObserver(object: RecyclerView.AdapterDataObserver() {     override fun onChanged() {         recycler_view_list.scrollToPosition(0)     }     override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {         recycler_view_list.scrollToPosition(0)     }     override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {         recycler_view_list.scrollToPosition(0)     }     override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {         recycler_view_list.scrollToPosition(0)     }     override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {         recycler_view_list.scrollToPosition(0)     }     override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {         recycler_view_list.scrollToPosition(0)     } })  viewModel.myLiveData.observe { this, Observer { myList ->          adapter.submitList(myList)  } 
like image 199
TheGraeme Avatar answered Sep 29 '22 07:09

TheGraeme