我尝试使用 AsyncListDiffer 提交相同的列表,但回收器视图总是自动滚动到顶部。当我调试时,在调用 areItemsTheSame 方法之前调用 submitList 后,我看到 recyclerview 自动滚动到顶部
class TestPlaceAdapter(
private val itemClickCallback: (TestPlaceUi) -> Unit
) : RecyclerView.Adapter<TestPlaceAdapter.ItemViewHolder>() {
private val differ = AsyncListDiffer(this, DiffCallback())
private val listTest = mutableListOf<TestPlaceUi>()
fun setData(listPlace: List<TestPlaceUi>) {
if (listTest.size == 0) {
listTest.addAll(listPlace)
differ.submitList(listTest)
} else {
val test = mutableListOf<TestPlaceUi>().apply {
addAll(listTest)
}
differ.submitList(test)
}
}
private class DiffCallback : DiffUtil.ItemCallback<TestPlaceUi>() {
override fun areItemsTheSame(oldItem: TestPlaceUi, newItem: TestPlaceUi): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: TestPlaceUi, newItem: TestPlaceUi): Boolean {
return oldItem == newItem
}
}
...
}
TestPlaceUi 是数据类,不会覆盖 equal 和 hashcode。