diffutil在嵌套回收器视图中工作不正常?

wrrgggsh  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(345)

所以,我有一个嵌套的回收器视图,每当我的子适配器列表项发生更改时,我就使用@update query更新我的数据库,我只想在我的回收器视图中看到更改,但问题是,一旦我更改列表项,我的回收器视图就会加倍,我正在使用diff utils设置数据,但这总是正确的。
下面是我的diffutil实现

import android.util.Log
import androidx.recyclerview.widget.DiffUtil

class DiffCallBack(
    private val oldList: List<TaskList>,
    private val newList: List<TaskList>
): DiffUtil.Callback(){

    override fun getOldListSize(): Int {
        return oldList.size
    }

    override fun getNewListSize(): Int {
        return newList.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition] === newList[newItemPosition]

    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        var value =  oldList[oldItemPosition].Taskid == newList[newItemPosition].Taskid
                && oldList[oldItemPosition].name == newList[newItemPosition].name
                && oldList[oldItemPosition].completed == newList[newItemPosition].completed
                && oldList[oldItemPosition].taskNoteId == newList[newItemPosition].taskNoteId

        return value
    }

}

下面是我调用的函数,用于在回收器视图中设置数据

fun setData(taskList:List<TaskList>){
    val toDoDiffUtil = DiffCallBack(dataList,taskList)
    val toDoDiffResult = DiffUtil.calculateDiff(toDoDiffUtil)
    this.dataList = taskList
    toDoDiffResult.dispatchUpdatesTo(this)

}

我的实现失败的原因是什么?我使用实时数据来观察要显示在父适配器下的列表中的更改。

mlmc2os5

mlmc2os51#

尝试使用 DiffUtil.ItemsCallBack 您可以执行以下操作

class YourDiff: DiffUtil.ItemCallback<YourDataClass>() {
    // use this to compare the id of the dataclass
    override fun areItemsTheSame(oldItem: YourDataClass, newItem: YourDataClass) =
        oldItem.id == newItem.id

    //use this to see if the contents are the same
    override fun areContentsTheSame(oldItem: YourDataClass, newItem: YourDataClass) =
        oldItem == newItem

}

然后将适配器从 ListAdapter 通过你的 YourDiff 对象

class YourAdapter: ListAdapter<YourDataClass, YourViewHolder>(YourDiff())

作为旁注,你不必重写 itemCount 如果你使用 ListAdapter 数据列表提交给适配器,如下所示

val adapter = YourAdapter()
 adapter.submitList(yourList)

检查
官方文件提供更多信息 ItemCallback 官方文件提供更多信息 ListAdapter

相关问题