gpt4 book ai didi

android - DiffUtil.calculateDiff 在 RecyclerView 中

转载 作者:行者123 更新时间:2023-11-29 23:45:55 25 4
gpt4 key购买 nike

下面的代码使用了两个列表之间的 DiffUtil.calculateDiff。每次我向下滚动列表时,新数据都会出现并添加到列表中。但是当结果通知更改时,适配器每次都会将我带到列表的顶部。

  1. 如何保持在添加新数据的位置?
  2. 这个例子是 DiffUtil.calculateDiff 的正确用法?或者我只是需要使用:

    companyList.addAll(companies);
    notifyDataSetChanged();

没有 DiffUtil.calculateDiff。

public void setProductList(final List<? extends Product> productList) {
if (mProductList == null) {
mProductList = productList;
notifyItemRangeInserted(0, productList.size());
} else {
DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
@Override
public int getOldListSize() {
return mProductList.size();
}

@Override
public int getNewListSize() {
return productList.size();
}

@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mProductList.get(oldItemPosition).getId() ==
productList.get(newItemPosition).getId();
}

@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
Product newProduct = productList.get(newItemPosition);
Product oldProduct = mProductList.get(oldItemPosition);
return newProduct.getId() == oldProduct.getId()
&& Objects.equals(newProduct.getDescription(), oldProduct.getDescription())
&& Objects.equals(newProduct.getName(), oldProduct.getName())
&& newProduct.getPrice() == oldProduct.getPrice();
}
});
mProductList.addAll(productList);
result.dispatchUpdatesTo(this);
}
}

最佳答案

新列表应包含您现有的项目和新的项目。因此,在追加新项目之前,旧列表应该是 mProductList 的副本,而在追加 productList 之后,新列表应该是 mProductList。但是,如果您根本不关心现有项目的变化,而只是追加到列表而不是排序/过滤,您可以只使用 notifyItemRangeInserted 来完成这项工作,而无需使用 DiffUtil,在这种情况下,您的 else block 将是:

int insertIndex = mProductList.size();
mProductList.addAll(productList);
notifyItemRangeInserted(insertIndex, productList.size());

关于android - DiffUtil.calculateDiff 在 RecyclerView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51411316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com