Android学习之旅

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

2019-09-25  本文已影响0人  pj0579

对于列表的使用频率很高,之前也了解过源码 但是过一段时间可能就忘的七七八八,所以写下这个笔记。
首先看下怎么绘制的 离不开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的参与绘制。
上一篇 下一篇

猜你喜欢

热点阅读