×

Android 踩坑记录(一)- Recyclerview的缓存机制

96
梨花满天便是雪
2016.08.24 08:50* 字数 1070

工作中遇到一些问题,以此记录问题的解决过程。

起因

上周因为业务需要,要完成一个展示优惠券信息的列表,列表内每张券都有详细信息,点击详细信息或者右面向下的箭头,可以展开相应优惠券的详细信息。展开的同时添加两个动画,展开的布局需要做缓慢展开的动画,向下展开的箭头需要做顺时针180度旋转变成向上收缩的状态。
当时看到这觉得没问题,一个RecyclerView就搞定了,在Adapter内对Item布局内的View做一个属性动画,简单省事。于是就开始愉快的敲着键盘写了起来,等写好一测试,Perfect!

正常效果图

展开收起展开毫无问题,刷新一下,(⊙o⊙)…问题来了,怎么箭头是向上的,我记得在onBindViewHolder里已经设置Item中箭头的状态是向下的。赶紧Debug一下,的确是设置了向下的图片。后来又分别展开了几个Item,刷新了一次列表,发现每次箭头方向错乱的位置还不固定。立马反应过来,估计是条目复用出的问题。立马开始查RecyclerView的Item缓存机制。

RecyclerView条目缓存机制

看了源码才发现,RecyclerView缓存基本上是通过三个内部类管理的,Recycler、RecycledViewPool和ViewCacheExtension。

** Recycler:**

Recycler用于管理已经废弃或者与RecyclerView分离的ViewHolder,为了方便理解这个类,整理了下面的资料,请结合Recycler的代码分析:

内部类的成员变量和他们的含义:

变量 作用
mChangedScrap 与RecyclerView分离的ViewHolder列表
mAttachedScrap 未与RecyclerView分离的ViewHolder列表
mCachedViews ViewHolder缓存列表
mViewCacheExtension 开发者可以控制的ViewHolder缓存的帮助类
mRecyclerPool ViewHolder缓存池

代码里面有个关键的方法,注释来自引文:

ViewHolder getScrapViewForPosition(int position, int type, boolean dryRun) {
    final int scrapCount = mAttachedScrap.size();
    // 在还未detach的废弃视图中查找出来一个类型匹配(无效类型)的view.
    for (int i = 0; i < scrapCount; i++) {
        final ViewHolder holder = mAttachedScrap.get(i);
        if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position && !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {
            if (type != INVALID_TYPE && holder.getItemViewType() != type) {
                break;
            }
      // 表明这个ViewHolder是从废弃的View集合中取出来的,可用于itemView的返回值。
            holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
            return holder;
        }
    }
    if (!dryRun) {
    // 找到已经隐藏,但是未被删除的view,然后将其detach掉,detach scrap中。
        View view = mChildHelper.findHiddenNonRemovedView(position, type);
        if (view != null) {
            final ViewHolder vh = getChildViewHolderInt(view);
            mChildHelper.unhide(view);
            int layoutIndex = mChildHelper.indexOfChild(view);
            mChildHelper.detachViewFromParent(layoutIndex);
            scrapView(view);
            vh.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP | ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
            return vh;
        }
    }
    // 在第一级视图缓存中查找.
    final int cacheSize = mCachedViews.size();
    for (int i = 0; i < cacheSize; i++) {
        final ViewHolder holder = mCachedViews.get(i);
    // invalid view holders may be in cache if adapter has stable ids as they can be
    // retrieved via getScrapViewForId
        if (!holder.isInvalid() && holder.getLayoutPosition() == position) {
            if (!dryRun) {
                mCachedViews.remove(i);
            }
            if (DEBUG) {
                Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
                      ") found match in cache: " + holder);
            }
            return holder;
        }
    }
    return null;
}

RecycledViewPool:

RecycledViewPool类是用来缓存Item用,是一个ViewHolder的缓存池,如果多个RecyclerView之间用setRecycledViewPool(RecycledViewPool)设置同一个RecycledViewPool,他们就可以共享Item。其实RecycledViewPool的内部维护了一个Map,里面以不同的viewType为Key存储了各自对应的ViewHolder集合。可以通过提供的方法来修改内部缓存的Viewholder。

下面来看下这个类的代码:

  public static class RecycledViewPool {
        private SparseArray<ArrayList<ViewHolder>> mScrap =
                new SparseArray<ArrayList<ViewHolder>>();
        private SparseIntArray mMaxScrap = new SparseIntArray();
        private int mAttachCount = 0;

        private static final int DEFAULT_MAX_SCRAP = 5;

        public void clear() {
            mScrap.clear();
        }

        public void setMaxRecycledViews(int viewType, int max) {
            mMaxScrap.put(viewType, max);
            final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
            if (scrapHeap != null) {
                while (scrapHeap.size() > max) {
                    scrapHeap.remove(scrapHeap.size() - 1);
                }
            }
        }

        public ViewHolder getRecycledView(int viewType) {
            final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
            if (scrapHeap != null && !scrapHeap.isEmpty()) {
                final int index = scrapHeap.size() - 1;
                final ViewHolder scrap = scrapHeap.get(index);
                scrapHeap.remove(index);
                return scrap;
            }
            return null;
        }

        int size() {
            int count = 0;
            for (int i = 0; i < mScrap.size(); i ++) {
                ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i);
                if (viewHolders != null) {
                    count += viewHolders.size();
                }
            }
            return count;
        }

        public void putRecycledView(ViewHolder scrap) {
            final int viewType = scrap.getItemViewType();
            final ArrayList scrapHeap = getScrapHeapForType(viewType);
            if (mMaxScrap.get(viewType) <= scrapHeap.size()) {
                return;
            }
            if (DEBUG && scrapHeap.contains(scrap)) {
                throw new IllegalArgumentException("this scrap item already exists");
            }
            scrap.resetInternal();
            scrapHeap.add(scrap);
        }

        void attach(Adapter adapter) {
            mAttachCount++;
        }

        void detach() {
            mAttachCount--;
        }


        /**
         * Detaches the old adapter and attaches the new one.
         * <p>
         * RecycledViewPool will clear its cache if it has only one adapter attached and the new
         * adapter uses a different ViewHolder than the oldAdapter.
         *
         * @param oldAdapter The previous adapter instance. Will be detached.
         * @param newAdapter The new adapter instance. Will be attached.
         * @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same
         *                               ViewHolder and view types.
         */
        void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
                boolean compatibleWithPrevious) {
            if (oldAdapter != null) {
                detach();
            }
            if (!compatibleWithPrevious && mAttachCount == 0) {
                clear();
            }
            if (newAdapter != null) {
                attach(newAdapter);
            }
        }

        private ArrayList<ViewHolder> getScrapHeapForType(int viewType) {
            ArrayList<ViewHolder> scrap = mScrap.get(viewType);
            if (scrap == null) {
                scrap = new ArrayList<ViewHolder>();
                mScrap.put(viewType, scrap);
                if (mMaxScrap.indexOfKey(viewType) < 0) {
                    mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP);
                }
            }
            return scrap;
        }
    }

这个类提供了四个公共方法:

返回值 方法 作用
void clear() 清空缓存池
RecyclerView.ViewHolder getRecycledView(int viewType) 得到一个viewType类型的Item
void putRecycledView(RecyclerView.ViewHolder scrap) 把viewType类型的Item放入缓存池
void setMaxRecycledViews(int viewType, int max) 设置对应viewType类型的Item的最大缓存数量

ViewCacheExtension:

我们先来看下代码:

    public abstract static class ViewCacheExtension {

        /**
         * Returns a View that can be binded to the given Adapter position.
         * <p>
         * This method should <b>not</b> create a new View. Instead, it is expected to return
         * an already created View that can be re-used for the given type and position.
         * If the View is marked as ignored, it should first call
         * {@link LayoutManager#stopIgnoringView(View)} before returning the View.
         * <p>
         * RecyclerView will re-bind the returned View to the position if necessary.
         *
         * @param recycler The Recycler that can be used to bind the View
         * @param position The adapter position
         * @param type     The type of the View, defined by adapter
         * @return A View that is bound to the given position or NULL if there is no View to re-use
         * @see LayoutManager#ignoreView(View)
         */
        abstract public View getViewForPositionAndType(Recycler recycler, int position, int type);
    }

ViewCacheExtension的代码一看什么都没有,没错这是一个需要开发者重写的类。上面Recycler里调用Recycler.getViewForPosition(int)方法获取View时,Recycler先检查自己内部的attached scrap和一级缓存,再检查ViewCacheExtension.getViewForPositionAndType(Recycler, int, int),最后检查RecyclerViewPool,从上面三个任何一个只要拿到View就不会调用下一个方法。所以我们可以重写getViewForPositionAndType(Recycler recycler, int position, int type),在方法里通过Recycler类控制View缓存。注意:如果你重写了这个类,Recycler不会在这个类中做缓存View的操作,是否缓存View完全由开发者控制。

总结

经过上面的分析,发现被属性动画修改过的ImageView在holder里,被RecyclerView缓存了之后,在别的Item又拿出来复用,虽然你设置了向下的背景图片,但是这个ImageView是做过180旋转的,所以设置一个向下的箭头图片还是向上的样子。
看来以后像旋转一类的简单的动画还是用View动画就可以了,复杂的动画再用属性动画。也可以重写Adapter里的void onViewDetachedFromWindow(VH holder)方法,在里面拿到holder找到修改过的ImageView,恢复他原来的属性,特别是有View被缓存复用的时候一定记得恢复原来的属性,否则就会出现这种混乱的情况。

引用

部分内容来自以下博客,特此鸣谢博客作者的分享:
RecyclerView解析
RecyclerView源码分析

本文内容采用 CC BY-NC-SA 3.0 进行许可, 转载请注明出处, 版权归本人及所有贡献者所有。

日记本
Web note ad 1