DiffUtils 的简单使用
DiffUtils 的使用起来也很简单,只需要简单的传入一个DiffCallback,重写其中的几个方法,DiffUtils 就能对比出新旧数据集差异,根据差异内容自动触发Adapter 的 增删改 通知,这也是我们在App 中最常用的使用方法。
在下面的示例中都使用Car
类型作为数据类。
data class Car(val band: String, val color: Int, val image: String, val price: Int) {
把Callback继续封装下,基本两行代码就可以实现adapter增删改的派发逻辑
val diffResult = DiffUtil.calculateDiff(SimpleDiffCallback(oldList, newList))
oldList.clear()
oldList.addAll(data)
diffResult.dispatchUpdatesTo(adapter)
//重写一个Callback 实现
class SimpleDiffCallback(
private val oldList: List,
private val newList: List
) : DiffUtil.Callback() {
override fun areItemsTheSame(lh: Int, rh: Int) = from[lh].band == to[rh].band
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun a