java - DiffUtil 未调用 onBindView 或刷新 ViewHolder
问题描述
我尝试使用 DiffUtil 方法更新我的列表,该列表始终包含 30 个项目,现在每个项目数据每分钟更新一次,但无法判断所有项目的数据是否都会更新,以避免滥用notifyDataSetChanged()
我创建了一个扩展 DiffUtil 的类。
public class DifUtil extends DiffUtil.Callback {
private final List<Asset> oldList, newList;
public DifUtil(List<Asset> newList, List<Asset> oldList) {
this.oldList = oldList;
this.newList = newList;
}
@Override
public int getOldListSize() {
return oldList.size();
}
@Override
public int getNewListSize() {
return newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).getId().equals(newList.get(newItemPosition).getId());
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).equals(newList.get(newItemPosition));
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
//you can return particular field for changed item.
return super.getChangePayload(oldItemPosition, newItemPosition);
}
}
添加新的公共函数以通过此通知适配器
public void updateList(List<Asset> newList) {
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DifUtil(newList, this.assetList));
this.assetList.clear();
this.assetList.addAll(newList);
diffResult.dispatchUpdatesTo(this);
}
覆盖另一个 onBindViewHolder(不使用有效负载时不确定是否需要)
onBindViewHolder(@NonNull AssetsAdapter.ViewHolder holder, int position, @NonNull List<Object> payloads)
然后通过调用更新列表
adapter.updateList(newAssetList);
列表的更新有效,但我只能通过滚动列表来查看这些新值,即使不回收视图(滚动时),我也需要查看更新,就像notifyItemChanged()
.
据我了解,调用dispatchUpdatesTo
应该处理和更新视图及其数据,或者我在这里遗漏了什么,请赐教。
解决方案
我通过关注此博客及其实现 DiffUtil 的方式设法使其工作。 https://www.journaldev.com/20873/android-recyclerview-diffutil
但是我没有执行克隆部分,因为它与我的情况无关。
奖金
有一个已知的错误,更新使列表在底部滚动。LayoutManager
我通过在这个 SO 答案中保存滚动状态来摆脱这个问题。
https://stackoverflow.com/a/44053550/11338467
所以我的适配器 DiffUtil 更新部分将是这个
public void updateList(List<Asset> newList) {
Parcelable recyclerViewState = layoutManager.onSaveInstanceState();
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DifUtil(newList, this.assetList));
diffResult.dispatchUpdatesTo(this);
this.assetList.clear();
this.assetList.addAll(newList);
layoutManager.onRestoreInstanceState(recyclerViewState);
}
推荐阅读
- java - 在下载完成之前显示进度条 - Android
- macros - __impl 在宏模式中的意义是什么?
- javascript - 过滤 2 个数组以在 React/JSX 中呈现一个值
- ios - 面料在 XCTest 上产生一些错误
- git - 如何使用“$ git commit”在消息开头引用问题(gitlab,github)?
- reactjs - Saga 观察者没有接收或处理分派的动作
- php - 正则表达式(PHP):避免捕获某个单词列表
- r - 防止 RStudio 中 kableExtra::kable_styling() 的长 html 输出
- javascript - 等待函数完成运行下一个
- c# - Xamarin.Forms 中的导航不起作用