//实现了老师的DiffUiDataCallback.UiDataDiffer
data class Main(val id: Int, val name: String) : DiffUiDataCallback.UiDataDiffer<Main> {
override fun isSame(old: Main): Boolean {
return this === old
}
override fun isUiContentSame(old: Main): Boolean {
return this == old
}
}
class Adapter(val dataList: MutableList<Main>) : RecyclerView.Adapter<Adapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val text = itemView.findViewById<TextView>(R.id.name)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.content_list_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Log.d("打印这个ViewHolder"," $holder")
holder.text.text = dataList[position].name
}
override fun getItemCount(): Int {
return dataList.size
}
}
val oldList = adapter.dataList
val newList = 刷新得到的新数据
// 进行数据对比
val callback: DiffUtil.Callback = DiffUiDataCallback(oldList, newList)
val result = DiffUtil.calculateDiff(callback)
//增量更新
adapter.dataList.clear()
adapter.dataList.addAll(newList)
result.dispatchUpdatesTo(adapter)
- 问题
方便测试就假设获取的数据始终只有一个,只是每次刷新来的数据name会变换,当我去刷新获取新数据并进行增量更新时,打印出会发现ViewHolder会有两个实例,使用diff进行增量刷新就有这个问题,正常的notifyDataSetChanged没有。 只大概知道RecyclerView获取缓存的问题
//看打印结果可以发现每刷新就会去从缓存中加载上一个ViewHolder,也就是在一个位置实际上创建了两个ViweHolder
打印这个ViewHolder ViewHolder{a42e991 position=0 id=-1, oldPos=-1, pLpos:-1 no parent}
打印这个ViewHolder ViewHolder{6c1c7c4 position=0 id=-1, oldPos=-1, pLpos:-1 no parent}
打印这个ViewHolder ViewHolder{a42e991 position=0 id=-1, oldPos=-1, pLpos:-1 no parent}
打印这个ViewHolder ViewHolder{6c1c7c4 position=0 id=-1, oldPos=-1, pLpos:-1 no parent}