首页 > 解决方案 > 从网络获取新数据后如何将 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

标签: androidandroid-recyclerviewandroid-diffutils

解决方案


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.
    }
}

推荐阅读