当用户到达滚动末尾以获得分页效果时,我正在更新我的列表。
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!recyclerView.canScrollVertically(RecyclerView.FOCUS_DOWN))
{ pageNumber++
loadIntroProducts(pageNumber)
}
}
}
这是我获取数据的地方
onProductSearchSuccess(data: Data){
productList.addAll(data.products)
productSimpleAdapter.updateProductItems(productList)
在适配器中,我使用 DiffUtil 设置新数据
fun updateProductItems(products: ArrayList<Products>) {
val diffCallback = ProductDiffCallback(this.productList, products)
val diffResult = DiffUtil.calculateDiff(diffCallback)
// this.productList.clear()
// this.productList.addAll(products)
setNewData(products)
diffResult.dispatchUpdatesTo(this)
}
private fun setNewData(newProducts: ArrayList<Products>) {
this.productList = newProducts
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
holder.bindView(holder.adapterPosition)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.isNullOrEmpty())
super.onBindViewHolder(holder, position, payloads)
else {
holder.bindView(holder.adapterPosition, payloads)
}
}
ProductDiffCallback
class ProductDiffCallback() :
DiffUtil.Callback() {
lateinit var oldProductList: ArrayList<Products>
lateinit var newProductList: ArrayList<Products>
constructor(oldProductList: ArrayList<Products>, newProductList: ArrayList<Products>) : this() {
this.oldProductList = oldProductList
this.newProductList = newProductList
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldProductList[oldItemPosition].productId == newProductList[newItemPosition].productId
}
override fun getOldListSize(): Int {
return oldProductList.size
}
override fun getNewListSize(): Int {
return newProductList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldProductList[oldItemPosition].productId == newProductList[newItemPosition].productId && oldProductList[oldItemPosition].numberOfCartItem == newProductList[newItemPosition].numberOfCartItem
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Bundle? {
val oldItem = oldProductList[oldItemPosition]
val newItem = oldProductList[newItemPosition]
val bundle = Bundle()
if (oldItem.numberOfCartItem != newItem.numberOfCartItem)
bundle.putInt("numberOfCartItems", newItem.numberOfCartItem)
return bundle
}
}
当我调试时,我得到了新列表包含所有项目但没有触发适配器类