DiffUtil.Callback 中有 2 个需要重写的函数:
areContentsTheSame(int oldItemPosition, int newItemPosition)
getChangePayload(int oldItemPosition, int newItemPosition)
我知道前者检查内容是否已更改,我想直接使用“==”来简单地比较它们是否是同一个实例,因为我相信我的项目在更新时将是一个新实例。但同样的比较在后一个函数中给出了不同的结果。 代码如下:
public class MyDiffUtilCallback extends DiffUtil.Callback {
List<App> mNewList;
List<App> mOldList;
public MyDiffUtilCallback(List<App> newList, List<App> oldList) {
mNewList = newList;
mOldList = oldList;
}
@Override
public int getOldListSize() {
return mOldList.size();
}
@Override
public int getNewListSize() {
return mNewList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mNewList.get(newItemPosition).id == mOldList.get(oldItemPosition).id;
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return mNewList.get(newItemPosition) == mOldList.get(oldItemPosition);
// This always returns false correctly whenever the item gets an update, it's working as expected
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
if (mNewList.get(newItemPosition) == mOldList.get(oldItemPosition)) {
return null; // But this is always being executed
}
return mNewList.get(newItemPosition).data; // This is never executed, why?
}
}
我不明白为什么旧项目和新项目之间的相同比较会给出不同的结果,父类(super class)是否修改了列表或其他内容?
最佳答案
来自 Android definition :
When areItemsTheSame(int, int) returns true for two items and areContentsTheSame(int, int) returns false for them, DiffUtil calls this method to get a payload about the change.
您应该尝试进行更详细的测试,我还发现了一篇关于 Medium 的好文章实现getChangePayload
。我希望这对您有帮助。
关于java - Android RecyclerView DiffUtil.Callback : areContentsTheSame() and getChangePayload() giving different comparison results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60911656/