android - 从网络获取新数据后如何将 RecyclerView 滚动到顶部;我正在使用 ListAdapter、DiffUtil
问题描述
我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(...)
class MyListAdapter<T, VH : ViewHolder>() :
PagedListAdapter<T, VH>(MyDiffUtilItemCallback()) {
...
override fun onCurrentListChanged(previousList: PagedList<T>, currentList: PagedList<T>) {
// Called when the current PagedList is updated.
}
}
推荐阅读
- mysql - 如何根据两个条件获取 COUNT(*)
- windows - VS2019 Xamarin iOS 模拟器“安装失败”
- javascript - 如何映射联系人数组以生成具有对象和属性的新数组?
- mysql - 在 Python 中保存在 MySql 中时,JSON 丢失了双引号。如何解决?
- android - 如何解决选择器中的反应原生空值?
- java - 使用 SMPP 发送 SMS
- java - 嵌套 For 循环的更好方法
- r - Mann-Whitney-Wilcoxon 检验两个不同样本大小的财务比率样本
- c# - SignalR:带有计时器的 System.ObjectDisposedException
- javascript - 删除后数据重复(Firebase)