android - Recyclerview DiffUtil 项目更新

标签 android kotlin android-recyclerview android-diffutils

我的回收器 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,而新的 productList4,5,6 。当你运行时

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

它将比较 1425 等,并得出一切都已更改的结论并且没有添加新的项目。 (注意:这是 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/

相关文章:

java - Android (ART) 崩溃并出现错误 JNI DETECTED ERROR IN APPLICATION : jstring is an invalid local reference

generics - 为什么我不能在这个 Rx 转换器中使用接口(interface)作为泛型类型?

java - 在 fragment 中设置布局管理器时,在 Recyclerview 上出现空指针异常

Android Recyclerview,okhttp,收到java.lang.ClassCastException错误

kotlin - 创建 getter/setter 但没有字段成员

android-viewpager - CoordinatorLayout 不能很好地与 NestedScrollView 和 viewpager 配合使用

android - Google GCM 实现是否需要 Api key

java - 获取 ArrayList 中文件的 lastModifiedDate() 和 fileSize()

android - Android 手机上的 ROS

java - Gradle 仅为公共(public)接口(interface)生成 sources.jar