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) }
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.
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.
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With