在顶部添加新项目后,Recycler视图未滚动到顶部,因为尚未对列表适配器进行更改 [英] Recycler view not scrolling to the top after adding new item at the top, as changes to the list adapter has not yet occurred

查看:94
本文介绍了在顶部添加新项目后,Recycler视图未滚动到顶部,因为尚未对列表适配器进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实时数据中首先获得包含新项目的新列表,然后使用其数据更新适配器

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

推荐答案

submitList在后台线程上工作,因此总会存在无法解决延迟的竞争条件.幸运的是,我们可以使用RecyclerView.AdapterDataObserver回调在列表计算完成时得到通知:

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

这篇关于在顶部添加新项目后,Recycler视图未滚动到顶部,因为尚未对列表适配器进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆