gpt4 book ai didi

android - Recyclerview DiffUtil 项目更新

转载 作者:行者123 更新时间:2023-12-02 12:46:11 27 4
gpt4 key购买 nike

我的回收站 View 中有无限滚动,因此,它会在有新数据时更新。我正在使用 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

最佳答案

您将之前的内容仅与新项目进行比较,而不是与添加了所有项目的列表进行比较。

想象一下如果 this.productList当前是 1,2,3 ,以及新的 productList4,5,6 .当你跑

DiffUtil.calculateDiff(ProductDiffUtil(this.productList, productList!!)

它将比较 14 , 25等,并得出结论,一切都发生了变化,并且没有添加新项目。 (注意:这是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com