最近公司在做性能优化的相关工作,在RecyclerView的优化方面,采用了DiffUtil来提升性能。
废话不多说,直接干代码
public class DiffHelper {
private DiffHelper() {
}
public static void diffTest(ShopAdapter adapter, List<String> oldList, List<String> newList) {
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(oldList, newList), true);
diffResult.dispatchUpdatesTo(adapter);
adapter.setData(newList);
}
public static class DiffCallBack extends DiffUtil.Callback {
private final List<String> oldDatas;
private final List<String> newDatas;
public DiffCallBack(List<String> oldDatas, List<String> newDatas) {
this.oldDatas = oldDatas;
this.newDatas = newDatas;
}
@Override
public int getOldListSize() {
return oldDatas.size();
}
@Override
public int getNewListSize() {
return newDatas.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldDatas.get(oldItemPosition).getClass().equals(newDatas.get(newItemPosition).getClass());
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return TextUtils.equals(oldDatas.get(oldItemPosition), newDatas.get(newItemPosition));
}
}
}
接下来是使用
recyclerView = findViewById(R.id.rv);
shopAdapter = new ShopAdapter(this, oldList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(shopAdapter);
findViewById(R.id.btn).setOnClickListener(view -> {
DiffHelper.diffTest(shopAdapter, shopAdapter.getData(), newList);
});
其实DiffUtil的使用还是比较简单的,可惜网上的大部分案例,给的示例代码很多都有问题,特别是必须要 dispatchUpdatesTo(adapter) 之后,记得更新adapter的缓存集合。否则是不会达到你期望的结果。DiffUtil只是一个计算差异的工具算法,与业务和UI界面都是解耦的,必须由开发者自己做一些数据的维护。