自Android5.0以来,RecyclerView渐渐取代ListView成为Android开发中使用最多的列表控件,对于RecyclerView的使用相信大家都不陌生,但对于RecyclerView的高效刷新,却是很多人不知道的。
Adapter.notifyDataSetChanged();
这种方式想必是大家曾经用的最多的一种刷新Adapter的方式,它的缺点很明显:
为了解决上述问题,RecyclerView推出了局部刷新的方式
Adapter.notifyItemChanged(int)
Adapter.notifyItemInserted(int)
Adapter.notifyItemRangeChanged(int, int)
Adapter.notifyItemRangeInserted(int, int)
Adapter.notifyItemRangeRemoved(int, int)
局部刷新只会刷新指定position的item,这样完美解决了上述简单粗暴刷新方式的缺点,但是:
Google似乎也注意到了这一点,因此在support-recyclerview-v7:24.2.0中,推出了一个用于计算哪些位置需要刷新的工具类:DiffUtil。
使用DiffUtil,有3个步骤
1.自实现DiffUtil.callback
private DiffUtil.Callback diffCallback = new DiffUtil.Callback() {
@Override
public int getOldListSize() {
// 返回旧数据的长度
return oldList == null ? 0 : oldList.size();
}
@Override
public int getNewListSize() {
// 返回新数据的长度
return newList == null ? 0 : newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
// 返回两个item是否相同
// 例如:此处两个item的数据实体是User类,所以以id作为两个item是否相同的依据
// 即此处返回两个user的id是否相同
return TextUtils.equals(oldList.get(oldItemPosition).getId(), newList.get(oldItemPosition).getId());
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
// 当areItemsTheSame返回true时,我们还需要判断两个item的内容是否相同
// 此处以User的age作为两个item内容是否相同的依据
// 即返回两个user的age是否相同
return oldList.get(oldItemPosition).getAge() == newList.get(newItemPosition).getAge();
}
};
2.计算得到DiffResult
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);
3.将DiffResult设置给Adapter
// 注意此处一定要将新数据设置给Adapter
// 否则会造成ui刷新了但数据未更新的bug
mAdapter.setData(newList);
diffResult.dispatchUpdatesTo(mAdapter);
这样我们就实现了局部刷新位置的计算和局部刷新的实现,相比notifyDataSetChanged(),性能大大提高。
本文到此结束?
不不不,还早着呢,咱们理智分析一下:
DiffUtil已经很好用了,但是有上述两个问题,想必Google的工程师也是看不下去的,虽然上述两个问题不难解决,但是很容易遗漏。
因此Google又推出了一个新的类AsyncListDiff
先来看一波AsyncListDiff的使用方式:
public class UserAdapter extends RecyclerView.Adapter {
private AsyncListDiffer mDiffer;
private DiffUtil.ItemCallback diffCallback = new DiffUtil.ItemCallback() {
@Override
public boolean areItemsTheSame(User oldItem, User newItem) {
return TextUtils.equals(oldItem.getId(), newItem.getId());
}
@Override
public boolean areContentsTheSame(User oldItem, User newItem) {
return oldItem.getAge() == newItem.getAge();
}
};
public UserAdapter() {
mDiffer = new AsyncListDiffer<>(this, diffCallback);
}
@Override
public int getItemCount() {
return mDiffer.getCurrentList().size();
}
public void submitList(List data) {
mDiffer.submitList(data);
}
public User getItem(int position) {
return mDiffer.getCurrentList().get(position);
}
@NonNull
@Override
public UserAdapter.UserViewHodler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user_list, parent, false);
return new UserViewHodler(itemView);
}
@Override
public void onBindViewHolder(@NonNull UserAdapter.UserViewHodler holder, int position) {
holder.setData(getItem(position));
}
class UserViewHodler extends RecyclerView.ViewHolder {
private TextView tvName;
private TextView tvAge;
public UserViewHodler(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
tvAge = itemView.findViewById(R.id.tv_age);
}
public void setData(User data) {
tvName.setText(data.getName());
tvAge.setText(String.valueOf(data.getAge()));
}
}
}
这里使用了一个简单的Adapter例子,不做封装,是为了更好地说明AsyncListDiffer。
不难看出,AsyncListDiffer的使用步骤:
ok,咱们看一下效果:
首先我们给Adapter设置数据
List users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User(String.valueOf(i), "用户" + i, i + 20));
}
mAdapter.submitList(users);
然后修改数据
List users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User(String.valueOf(i), "用户" + i, i % 3 == 0 ? i + 10: i + 20));
}
mAdapter.submitList(users);
跑起来看一哈
ok,我们看到只有被3整除的position被刷新了,完美的局部刷新。
那么问题来了,AsyncListDiffer是如何解决我们上述的两个问题的呢?
我们走进AsyncListDiffer的源码看一下:
public class AsyncListDiffer {
private final ListUpdateCallback mUpdateCallback;
private final AsyncDifferConfig mConfig;
public AsyncListDiffer(@NonNull RecyclerView.Adapter adapter,
@NonNull DiffUtil.ItemCallback diffCallback) {
mUpdateCallback = new AdapterListUpdateCallback(adapter);
mConfig = new AsyncDifferConfig.Builder<>(diffCallback).build();
}
private List mList;
private List mReadOnlyList = Collections.emptyList();
private int mMaxScheduledGeneration;
public List getCurrentList() {
return mReadOnlyList;
}
public void submitList(final List newList) {
if (newList == mList) {
// 如果新旧数据相同,则啥事不做
return;
}
// 用于控制计算线程,防止在上一次submitList未完成时,
// 又多次调用submitList,这里只返回最后一个计算的DiffResult
final int runGeneration = ++mMaxScheduledGeneration;
if (newList == null) {
// 如果新数据集为空,此种情况不需要计算diff
// 直接清空数据即可
// 通知item remove
mUpdateCallback.onRemoved(0, mList.size());
mList = null;
mReadOnlyList = Collections.emptyList();
return;
}
if (mList == null) {
// 如果旧数据集为空,此种情况不需要计算diff
// 直接将新数据添加到旧数据集即可
// 通知item insert
mUpdateCallback.onInserted(0, newList.size());
mList = newList;
mReadOnlyList = Collections.unmodifiableList(newList);
return;
}
final List oldList = mList;
// 在子线程中计算DiffResult
mConfig.getBackgroundThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
@Override
public int getOldListSize() {
return oldList.size();
}
@Override
public int getNewListSize() {
return newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mConfig.getDiffCallback().areItemsTheSame(
oldList.get(oldItemPosition), newList.get(newItemPosition));
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return mConfig.getDiffCallback().areContentsTheSame(
oldList.get(oldItemPosition), newList.get(newItemPosition));
}
});
// 在主线程中更新数据
mConfig.getMainThreadExecutor().execute(new Runnable() {
@Override
public void run() {
if (mMaxScheduledGeneration == runGeneration) {
latchList(newList, result);
}
}
});
}
});
}
private void latchList(@NonNull List newList, @NonNull DiffUtil.DiffResult diffResult) {
diffResult.dispatchUpdatesTo(mUpdateCallback);
mList = newList;
mReadOnlyList = Collections.unmodifiableList(newList);
}
}
线程部分源码:
private static class MainThreadExecutor implements Executor {
final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(@NonNull Runnable command) {
mHandler.post(command);
}
}
@NonNull
public AsyncDifferConfig build() {
if (mMainThreadExecutor == null) {
mMainThreadExecutor = sMainThreadExecutor;
}
if (mBackgroundThreadExecutor == null) {
synchronized (sExecutorLock) {
if (sDiffExecutor == null) {
sDiffExecutor = Executors.newFixedThreadPool(2);
}
}
mBackgroundThreadExecutor = sDiffExecutor;
}
return new AsyncDifferConfig<>(
mMainThreadExecutor,
mBackgroundThreadExecutor,
mDiffCallback);
}
ui刷新部分源码:
public final class AdapterListUpdateCallback implements ListUpdateCallback {
@NonNull
private final RecyclerView.Adapter mAdapter;
public AdapterListUpdateCallback(@NonNull RecyclerView.Adapter adapter) {
mAdapter = adapter;
}
@Override
public void onInserted(int position, int count) {
mAdapter.notifyItemRangeInserted(position, count);
}
@Override
public void onRemoved(int position, int count) {
mAdapter.notifyItemRangeRemoved(position, count);
}
@Override
public void onMoved(int fromPosition, int toPosition) {
mAdapter.notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onChanged(int position, int count, Object payload) {
mAdapter.notifyItemRangeChanged(position, count, payload);
}
}
源码实现很简单,总结一下: