【发布时间】:2026-01-22 01:15:01
【问题描述】:
我的 recyclerview 中有无限滚动,所以当有新数据时它会更新。我正在使用 DiffUtil 更新 recyclerview 中的数据。 DiffUtil 确实会更新数据,但只要有更新数据,recyclerview 就会滚动到顶部,看起来就像“使用 notifydatasetchanged()”。这是我的 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
【问题讨论】:
-
使用 notifyitemrangeinserted 方法。
-
我最初使用的是 notifyItemRangeInserted() 但 diffUtil 使列表更快,所以我正在尝试使用它。
-
用
DiffUtil.ItemCallback<T>()代替DiffUtil.Callback怎么样。 -
你是如何实现适配器的?你是使用分页库还是定制的?
标签: android kotlin android-recyclerview android-diffutils