[英]DiffUtil.calculateDiff In RecyclerView
我下面的代碼在兩個列表之間使用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);
}
}
新列表應同時包含現有項目和新項目。 因此,在添加新項目之前,舊列表應該是mProductList
的副本, mProductList
在添加mProductList
之后,新列表應該是productList
。 但是,如果你不關心在所有改變現有的項目,只是追加到列表中,而不是排序/過濾,你可能只是做與工作notifyItemRangeInserted
不使用DiffUtil
,在這種情況下,你的else塊將是:
int insertIndex = mProductList.size();
mProductList.addAll(productList);
notifyItemRangeInserted(insertIndex, productList.size());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.