如何从网络中获取新数据后将RecyclerView滚动到顶部;我正在使用ListAdapter,DiffUtil

问题描述 投票:0回答:1

我正在使用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

android android-recyclerview android-diffutils
1个回答
0
投票

ListAdapter不提供让您知道差异计算何时完成的方法。您可以改用PagedListAdapter并在适配器中使用submitList(myList, callback)或覆盖onCurrentListChanged(...)方法:

© www.soinside.com 2019 - 2024. All rights reserved.