当我用新项目更新 Android RecyclerView 时,旧视图会在新视图覆盖它们之前短暂显示
When I update Android RecyclerView with new items, old views are briefly shown before new views override them
我的适配器中有以下代码:
private val items: MutableList<T>
open fun setItems(items: List<T>?) {
this.items.clear()
if (items != null)
this.items.addAll(items)
notifyDataSetChanged()
}
当相应的 RecyclerView 第一次显示时,它会按预期充满我从网络获得的数据的视图。
当我从网络请求新数据时,我让回收站视图 visibility = gone 并请求数据。当我获取新的网络数据并使用上面的 setItems() 更新适配器时,我再次使回收器视图可见。问题是,虽然屏幕按预期更新了新视图,但我在显示新视图之前得到了一个简短的 "flash" 显示旧视图。我可以通过在 setItems 之前调用 recyclerView.removeAllViews() 来修复它,但是有更好的方法来处理它吗?我不确定这里的根本原因是什么,我唯一的想法是 notifyDataSetChanged 更新太慢。
发生这种情况是因为您在调用 notifyDataSetChanged()
之前将 RecyclerView 的可见性设置为消失。根据 notifyDataSetChanged()
上的文档:
LayoutManagers will be forced to fully rebind and relayout all
visible views. RecyclerView will attempt to synthesize visible
structural change events for adapters that report that they have
stable IDs when this method is used.
要解决此问题,您可以在加载数据时清除回收器视图项目,并在加载数据后更新它。这样您就不必操纵回收器视图的可见性。
此外,为了提高性能,您应该考虑在适配器中使用更具体的更改事件:
private val items: MutableList<T>
open fun setItems(items: List<T>?) {
clearItems()
val newSize = items.size
if (items != null)
this.items.addAll(items)
notifyItemRangeInserted(0, newSize)
}
fun clearItems() {
val oldSize = this.items.size
this.items.clear()
notifyItemRangeRemoved(0, oldSize)
}
我的适配器中有以下代码:
private val items: MutableList<T>
open fun setItems(items: List<T>?) {
this.items.clear()
if (items != null)
this.items.addAll(items)
notifyDataSetChanged()
}
当相应的 RecyclerView 第一次显示时,它会按预期充满我从网络获得的数据的视图。 当我从网络请求新数据时,我让回收站视图 visibility = gone 并请求数据。当我获取新的网络数据并使用上面的 setItems() 更新适配器时,我再次使回收器视图可见。问题是,虽然屏幕按预期更新了新视图,但我在显示新视图之前得到了一个简短的 "flash" 显示旧视图。我可以通过在 setItems 之前调用 recyclerView.removeAllViews() 来修复它,但是有更好的方法来处理它吗?我不确定这里的根本原因是什么,我唯一的想法是 notifyDataSetChanged 更新太慢。
发生这种情况是因为您在调用 notifyDataSetChanged()
之前将 RecyclerView 的可见性设置为消失。根据 notifyDataSetChanged()
上的文档:
LayoutManagers will be forced to fully rebind and relayout all visible views. RecyclerView will attempt to synthesize visible structural change events for adapters that report that they have stable IDs when this method is used.
要解决此问题,您可以在加载数据时清除回收器视图项目,并在加载数据后更新它。这样您就不必操纵回收器视图的可见性。
此外,为了提高性能,您应该考虑在适配器中使用更具体的更改事件:
private val items: MutableList<T>
open fun setItems(items: List<T>?) {
clearItems()
val newSize = items.size
if (items != null)
this.items.addAll(items)
notifyItemRangeInserted(0, newSize)
}
fun clearItems() {
val oldSize = this.items.size
this.items.clear()
notifyItemRangeRemoved(0, oldSize)
}