【问题标题】:what is the best way to update a list with diffUtils用 diffUtils 更新列表的最佳方法是什么
【发布时间】:2021-10-03 15:44:13
【问题描述】:

我想用 diffUtils 更新列表项,但是在我用 diffDiffUtils 设置列表后,如下所示:

val coinsDiffUtil = DataDiffUtilCallBack(itemList, newData)
val diffUtilResult = DiffUtil.calculateDiff(coinsDiffUtil)
itemList = ArrayList(newData)
diffUtilResult.dispatchUpdatesTo(this)

diff util 不会更新 recyclerView 项目,所以我使用这样的函数:

fun updateItem(item: Model) {
    val index = itemList.indexOfFirst {
        it.id == item.id
    }
   itemList[index].enabled = item.enabled
   notifyItemChanged(index)
}

【问题讨论】:

  • 使用 ListAdapter 作为 RecyclerView 的适配器。您将 DiffUtil 回调传递给它的构造函数。然后,您需要做的就是在适配器上调用submitList,每次发生变化时使用新的数据列表,它会自动更新 RecyclerView。

标签: android kotlin android-recyclerview android-diffutils


【解决方案1】:

最简单的方法是使用ListAdapter 并将您的DiffUtil.ItemCallback 传递给它ref , 例子

class RecyclerViewTodoAdapter : ListAdapter<Task, RecyclerViewTodoAdapter.LayoutViewHolder>(
    DIFF_CALLBACK
) {

    companion object {
        val DIFF_CALLBACK: DiffUtil.ItemCallback<Task> = object : DiffUtil.ItemCallback<Task>() {
            override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
                return oldItem.equals(newItem)
            }

            override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
                // check for contents
                return oldItem.taskName == newItem.taskName &&
                        oldItem.summary == newItem.summary &&
                        oldItem.importance == newItem.importance
            }
        }
    }
    // your generic code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多