Android RecyclerView中的DiffUtil.calculateDiff

Android RecyclerView中的DiffUtil.calculateDiff,android,android-recyclerview,Android,Android Recyclerview,下面的代码在两个列表之间使用DiffUtil.calculateDiff。每次我向下滚动列表,新数据就会出现并添加到列表中。但当结果通知更改时,适配器每次都会将我带到列表的顶部 我怎样才能保持添加新数据的位置 这个例子是DiffUtil.calculateDiff的正确用法?或者我只需要使用: companyList.addAll(companies); notifyDataSetChanged(); 没有DiffUtil.calculateDiff public void setProdu

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

  • 我怎样才能保持添加新数据的位置
  • 这个例子是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);
        }
    }
    

    public void setProductList(最终列表新列表应包含现有项目和新项目。因此,在添加新项目之前,旧列表应为
    MPProductList
    的副本,而在添加
    productList
    之后,新列表应为
    MPProductList
    。但是如果您根本不关心现有项目的更改,而只是一个简单的列表p转到列表而不是排序/筛选,您可能只需使用
    notifyItemRangeInserted
    而不使用
    DiffUtil
    ,在这种情况下,您的else块将是:

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