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

后端 未结 5 1474
无人及你
无人及你 2021-02-07 06:37

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          


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 06:53

    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) 
    }
    

提交回复
热议问题