Android RecyleView源码重新解读,绘制与缓存机制

对于列表的使用频率很高,之前也了解过源码 但是过一段时间可能就忘的七七八八,所以写下这个笔记。
首先看下怎么绘制的 离不开View的 Measure Layout Draw三部曲
onMeasure的执行逻辑

protected void onMeasure(int widthSpec, int heightSpec) {
       if (mLayout == null) {
            // 没有设置layoutManager的话 直接显示空白
           defaultOnMeasure(widthSpec, heightSpec);
           return;
       }
       if (mLayout.mAutoMeasure) {
           // mAutoMeasure 默认为true构造函数里赋值了
           final int widthMode = MeasureSpec.getMode(widthSpec);
           final int heightMode = MeasureSpec.getMode(heightSpec);
           final boolean skipMeasure = widthMode == MeasureSpec.EXACTLY
                   && heightMode == MeasureSpec.EXACTLY;
            // skipMeasure 一般是true(match_parent和固定值的时候)子view的measure在onLayout执行
           mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
           if (skipMeasure || mAdapter == null) {
               return;
           }
      .........
   }

onLayout的执行逻辑

1.protected void onLayout(boolean changed, int l, int t, int r, int b) {
          ...
        dispatchLayout();
         ...
    }
2.void dispatchLayout() {
        .....
        if (mState.mLayoutStep == State.STEP_START) {
            // 更新适配器 选择动画等设置保存操作
            dispatchLayoutStep1(); 
            mLayout.setExactMeasureSpecsFrom(this);
            // 真正的measure layout在这里执行 
            dispatchLayoutStep2();
        } else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth()
                || mLayout.getHeight() != getHeight()) {
            // First 2 steps are done in onMeasure but looks like we have to run again due to
            // changed size.
            mLayout.setExactMeasureSpecsFrom(this);
            dispatchLayoutStep2();
        } else {
            // always make sure we sync them (to ensure mode is exact)
            mLayout.setExactMeasureSpecsFrom(this);
        }
        dispatchLayoutStep3();
    }

// 真正的measure layout在这里执行 
3.private void dispatchLayoutStep2() {
        .....
        mState.mItemCount = mAdapter.getItemCount();
         ........
        // 以LinearManager为例 看看它的onLayoutChildren方法
        mLayout.onLayoutChildren(mRecycler, mState); 
    }

// 以LinearManager为例
4.public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
     .....
     // 这个方法进行了measure layout 最重要的缓存机制也在里面
     fill(recycler, mLayoutState, state, false);
}
5.int fill(RecyclerView.Recycler recycler, LayoutState layoutState,RecyclerView.State state, boolean stopOnFocusable){
           ......
            // 这个方法进行了measure layout 最重要的缓存机制也在里面
            layoutChunk(recycler, state, layoutState, layoutChunkResult);
}
6.void layoutChunk(RecyclerView.Recycler recycler, RecyclerView.State state,
                     LayoutState layoutState, LayoutChunkResult result) {
        //next 包含缓存机制
        View view = layoutState.next(recycler);
        ........
        // measure
        measureChildWithMargins(view, 0, 0);
        ......
        //layout
        layoutDecoratedWithMargins(view, left, top, right, bottom);
        ......
    }

Draw 过程比较正常

public void draw(Canvas c) {
        // 默认实现
        super.draw(c);
       // 添加装饰器
        final int count = mItemDecorations.size();
        for (int i = 0; i < count; i++) {
            mItemDecorations.get(i).onDrawOver(c, this, mState);
        }
      .... 
}

然后说下他的缓存机制
先来看下刚才的next方法

View next(RecyclerView.Recycler recycler) {
            if (mScrapList != null) {
                return nextViewFromScrapList();
            }
            final View view = recycler.getViewForPosition(mCurrentPosition);
            mCurrentPosition += mItemDirection;
            return view;
        }

点击 getViewForPosition的调用链,最后到
tryGetViewHolderForPositionByDeadline方法
Attempts to get the ViewHolder for the given position, either from the Recycler scrap, cache, the RecycledViewPool, or creating it directly.
要嘛从缓存中取 如果没有的话直接创建。
那到底缓存是个什么样的机制呢?往下看,这个方法特别长

 ViewHolder tryGetViewHolderForPositionByDeadline(int position,
                boolean dryRun, long deadlineNs) {
           ....
            ViewHolder holder = null;
            // 0) 这是一个预布局过程 还没有真正形成显示,isPreLayout()在有动画的阶段才为true  和主要的的缓存机制关系不大
            if (mState.isPreLayout()) {
                holder = getChangedScrapViewForPosition(position);
                fromScrapOrHiddenOrCache = holder != null;
            }
             // 1) 第一次 从 scrap/hidden list/cache的地方获取
            if (holder == null) {
                 // dryRun 默认false 默认会调用findHiddenNonRemovedView查找holder
                // 这个方法第一步会寻找合适的mAttachedScrap的holder, 没有符合的话,继续查找findHiddenNonRemovedView,还是没有的话会去mCachedViews里查找,最后如果没有查找到返回null。
                holder = getScrapOrHiddenOrCachedHolderForPosition(position, dryRun);
               // 合法判断  不合法的话 holder = null;
                .......
                final int type = mAdapter.getItemViewType(offsetPosition);
                // 2) 第二次  Find from scrap/cache via stable ids, if exists 这次获取的时候会考虑type id流程和第一次差不多。
                if (mAdapter.hasStableIds()) {
                    holder = getScrapOrCachedViewForId(mAdapter.getItemId(offsetPosition),
                            type, dryRun);
                    if (holder != null) {
                        // update position
                        holder.mPosition = offsetPosition;
                        fromScrapOrHiddenOrCache = true;
                    }
                }
                // 3) 从自定义缓存取 一般mViewCacheExtension为null 需要自己扩展 缓存算法 数据结构需要自己控制 没有使用过
                if (holder == null && mViewCacheExtension != null) {
                    final View view = mViewCacheExtension
                            .getViewForPositionAndType(this, position, type);
                    if (view != null) {
                        holder = getChildViewHolder(view);
                        if (holder == null) {
                            throw new IllegalArgumentException("getViewForPositionAndType returned"
                                    + " a view which does not have a ViewHolder"
                                    + exceptionLabel());
                        } else if (holder.shouldIgnore()) {
                            throw new IllegalArgumentException("getViewForPositionAndType returned"
                                    + " a view that is ignored. You must call stopIgnoring before"
                                    + " returning this view." + exceptionLabel());
                        }
                    }
                }
                if (holder == null) { // fallback to pool
                     ....
                    // 4)从  RecycledViewPool取缓存
                    holder = getRecycledViewPool().getRecycledView(type);
                    if (holder != null) {
                        holder.resetInternal();
                        if (FORCE_INVALIDATE_DISPLAY_LIST) {
                            invalidateDisplayListInt(holder);
                        }
                    }
                }
                if (holder == null) {
                    long start = getNanoTime();
                    if (deadlineNs != FOREVER_NS
                            && !mRecyclerPool.willCreateInTime(type, start, deadlineNs)) {
                        // abort - we have a deadline we can't meet
                        return null;
                    }
                    // 5) 重新创建一个holder
                    holder = mAdapter.createViewHolder(RecyclerView.this, type);
                    if (ALLOW_THREAD_GAP_WORK) {
                        // only bother finding nested RV if prefetching
                        RecyclerView innerView = findNestedRecyclerView(holder.itemView);
                        if (innerView != null) {
                            holder.mNestedRecyclerView = new WeakReference<>(innerView);
                        }
                    }

                    long end = getNanoTime();
                    mRecyclerPool.factorInCreateTime(type, end - start);
                    if (DEBUG) {
                        Log.d(TAG, "tryGetViewHolderForPositionByDeadline created new ViewHolder");
                    }
                }
            }
            .......
            return holder;
        }

绘制机制 缓存机制总结

有以下几点:
1.缓存有四个等级:mAttachedScrap,mCacheViews,ViewCacheExtension,RecycledViewPool查找顺序也是按照列出的顺序。
mAttachedScrap:缓存的是还显示在屏幕上的holder,滑动过程中不会在这个里执行,局部更新item的时候会用上。
mCacheViews:不需要重新Bind,缓存的是移出屏幕的holder,默认最大值2
ViewCacheExtension:自定义缓存机制 需要深入理解
RecycledViewPool:数据会被清空,需要重新bind 会根据不同type创建不同的list存放ViewHolder,mCacheViews满了之后,旧的holder会到pool里来,默认最大值5

  1. 绘制过程重点是LayoutManager的参与绘制。
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容

  • 这个世上, 没有不自私的人。 因为自私,所以贪图, 因为贪图,所以疲惫, 因为疲惫,所以流泪。 世上的事, 根本不...
    键盘弹奏者阅读 676评论 3 9
  • 2018-02-27 姓名:郭祥华 组别:315期六项精进努力一组 【日精进打卡第115天】 【知~学习】 背诵《...
    华英雄_712d阅读 226评论 0 0
  • 16岁的女孩莉迪亚死了,死于溺水。 警察根据现场证据分析,初步判断死因是自杀。然而,她的家人都不相信。 她是那么一...
    鱼鲜支阅读 534评论 5 5
  • 新兰蔻气垫CC的质感非常轻薄,手指一按,即可感受到轻薄的液体,最最重要的特点是:非常非常的水润,持久的水润。盒子颜...
    Amybubu阅读 117评论 0 0
  • 今天测试人员使用ie测试vue项目,出现bug然后我自己npm run build 启动项目,启动失败 据说是因为...
    JennyGao66阅读 1,058评论 1 0