我正在使用ListAdapter
更新RecyclerView
。
我的适配器外观
class MyListAdapter<T, VH : ViewHolder>() :
ListAdapter<T, VH>(MyDiffUtilItemCallback()) {
...
...
Adapter code
...
...
class MyDiffUtilItemCallback : DiffUtil.ItemCallback<Product>() {
override fun areItemsTheSame(
oldItem: Product?,
newItem: Product?
): Boolean {
if (oldItem != null && newItem != null) {
return oldItem.productId == newItem.productId
}
return false
}
override fun areContentsTheSame(
oldItem: Product?,
newItem: Product?
): Boolean {
if (oldItem != null && newItem != null) {
return oldItem.productId == newItem.productId &&
oldItem.name== newItem.name && oldItem.weight == newItem.weight
}
return false
}
}
}
我正在实现类似Google的搜索,用户可以在其中输入搜索查询,并且当用户暂停API时,该查询将被调用,并且RecyclerView
会更新结果。现在,如果用户再次追加查询,数据将被提取并添加到RecyclerView
。在这里,我要RecyclerView
滚动到最高位置。
以下代码对我不起作用:
productAdapter.submitList(productList)
rvBillingProduct.smoothScrollToPosition(0)
由于在将数据添加到列表之前正在执行后台线程rvBillingProduct.smoothScrollToPosition(0)
上的差异的计算。
我不确定DiffUtils结果计算完成后如何获取回调,以便可以滚动RecyclerView
ListAdapter
不提供让您知道差异计算何时完成的方法。您可以改用PagedListAdapter
并在适配器中使用submitList(myList, callback)
或覆盖onCurrentListChanged(...)
方法: