我的回收器 View 中有无限滚动,因此,当有新数据时它会更新。我正在使用 DiffUtil 更新回收器 View 中的数据。 DiffUtil 确实会更新数据,但每当有更新数据时,recyclerview 就会滚动到顶部,看起来就像“使用 notificationdatasetchanged()”。这是我的 DiffUtil 和用于更新数据的适配器。
class ProductDiffUtil(
val oldProductList: List<ProductModel>, val newProductList: List<ProductModel>
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldProductList[oldItemPosition].id == newProductList[newItemPosition].id
}
override fun getOldListSize(): Int = oldProductList.size
override fun getNewListSize(): Int = newProductList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldProductList[oldItemPosition] == newProductList[newItemPosition]
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
return super.getChangePayload(oldItemPosition, newItemPosition)
}
}
这是我用于更新数据的适配器
fun addProductList(productList: List<ProductModel>?) {
val diffResult = DiffUtil.calculateDiff(ProductDiffUtil(this.productList, productList!!))
this.productList.addAll(productList)
diffResult.dispatchUpdatesTo(this)
}
请帮我解决这个问题。当我使用notifyItemRangeChanged()时它工作正常...那么我应该使用什么来更新recyclerview中的数据以获得最佳实践。
https://drive.google.com/open?id=1SapXW2wusmTpyGCRA9fa0aSLCYNL1fzN
最佳答案
您仅将以前的内容与新项目进行比较,而不是与添加了所有项目的列表进行比较。
想象一下,如果 this.productList
当前为 1,2,3
,而新的 productList
为 4,5,6
。当你运行时
DiffUtil.calculateDiff(ProductDiffUtil(this.productList, productList!!)
它将比较 1
与 4
、2
与 5
等,并得出一切都已更改的结论并且没有添加新的项目。 (注意:这是 DiffUtil 算法的过度简化,但可以说明这一点)
相反,如果您想使用 DiffUtil:
val oldList = ArrayList(productList)
this.productList.addAll(productList)
val diffResult = DiffUtil.calculateDiff(ProductDiffUtil(oldList, productList!!)
diffResult.dispatchUpdatesTo(this)
或者,由于您确切知道添加了多少项目以及添加位置,因此只需使用 notifyItemRangeInserted
并避免复制:
val oldSize = this.productList.size
this.productList.addAll(productList)
notifyItemRangeInserted(oldSize, productList.size)
关于android - Recyclerview DiffUtil 项目更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60313178/