RecyclerView小知识

185 阅读1分钟

ListAdapter

注意事项:

1. submit一个集合,需要注意,不能是同一个集合对象,否则数据不会刷新

原因可以查看源码,如下,第一步就是比较两次的list是否一样

public void submitList(@Nullable final List<T> newList,
        @Nullable final Runnable commitCallback) {
    // incrementing generation means any currently-running diffs are discarded when they finish
    final int runGeneration = ++mMaxScheduledGeneration;

    if (newList == mList) {
        // nothing to do (Note - still had to inc generation, since may have ongoing work)
        if (commitCallback != null) {
            commitCallback.run();
        }
        return;
    }

2. Diff的问题

protected ListAdapter(@NonNull DiffUtil.ItemCallback<T> diffCallback) 

callback的三个方法分析

public abstract static class ItemCallback<T> {

//为true的话item就不会整体刷新了
public abstract boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem);

//这个为false,并且下边的payload返回不为空,可以进行局部刷新
public abstract boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem);

public Object getChangePayload(@NonNull T oldItem, @NonNull T newItem) {
    return null;
}


override fun onBindViewHolder(holder: MyHolder, position: Int)

//根据payloads不为null来进行局部刷新
override fun onBindViewHolder(holder: MyHolder, position: Int, payloads: MutableList<Any>) {
    super.onBindViewHolder(holder, position, payloads)
}

3 不刷新的问题

还有一种可能,比如 首先传个list集合进去,完事修改了list里的某条数据,因为不能是同一个集合,所以就new一个list再把旧的list数据addall,你以为可行,其实不可行。为啥?因为这两集合的数据现在是一模一样的,所以不会刷新。

4 适合哪些情况

listAdapter 比较适合那种从数据库查询数据的,这样每次出来的集合都是全新的,和旧数据没关系。或者从网络获取的也一样,都是全新的集合。