RecyclerView源码分析(三)测绘流程下篇

996 阅读4分钟

上一篇从RecyclerView的源码牵出了测量和布局的核心逻辑都在dispatchLayoutStep系列方法中。这篇我们就分析下dispatchLayoutStep系列方法。

dispatchLayoutStep1

//布局的第一步; - 处理适配器更新 - 决定应该运行哪个动画 - 保存有关当前视图的信息 - 如有必  
//要,运行预测布局并保存其信息
private void dispatchLayoutStep1() {
        mState.assertLayoutStep(State.STEP_START);
        fillRemainingScrollValues(mState);
        mState.mIsMeasuring = false;
        // 阻止外部requestLayout调用,上一篇说过
        startInterceptRequestLayout();
        mViewInfoStore.clear();
        // 表示正在进行layout,上面说过
        onEnterLayoutOrScroll();
        // 处理适配器更新和动画标记
        processAdapterUpdatesAndSetAnimationFlags();
        saveFocusInfo();
        mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;
        mItemsAddedOrRemoved = mItemsChanged = false;
        mState.mInPreLayout = mState.mRunPredictiveAnimations;
        mState.mItemCount = mAdapter.getItemCount();
        findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);

        if (mState.mRunSimpleAnimations) {
            // 是否运行动画
            。。。
        }
        if (mState.mRunPredictiveAnimations) {
            // 是否运行预测性动画
            。。。
        } else {
            clearOldPositions();
        }
        
        //恢复上面的拦截和条件判断
        onExitLayoutOrScroll();
        stopInterceptRequestLayout(false);
        // 设置标记
        mState.mLayoutStep = State.STEP_LAYOUT;
    }

上面说到,dispatchLayoutStep1主要是存储一些UI数据。代码的注释已经很清楚了。 我们看到这个方法内部主要通过两个条件进行判断,一个是mRunSimpleAnimations,也就是是否运行动画。还有一个是mRunPredictiveAnimations,也就是是否进行预测性动画。

预测性动画会在以后专门讲动画的时候详解。
processAdapterUpdatesAndSetAnimationFlags方法内部主要处理适配器更新和处理动画标记。

     private void processAdapterUpdatesAndSetAnimationFlags() {
        。。。
        boolean animationTypeSupported = mItemsAddedOrRemoved || mItemsChanged;
        mState.mRunSimpleAnimations = mFirstLayoutComplete
                && mItemAnimator != null
                && (mDataSetHasChangedAfterLayout
                || animationTypeSupported
                || mLayout.mRequestedSimpleAnimations)
                && (!mDataSetHasChangedAfterLayout
                || mAdapter.hasStableIds());
        mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations
                && animationTypeSupported
                && !mDataSetHasChangedAfterLayout
                && predictiveItemAnimationsEnabled();
    }

mRunSimpleAnimations的赋值

  • mFirstLayoutComplete必须为true,这个值实在onLayout完成后赋值的,所以第一次测绘的时候,是没有动画的。这里可以得到证明,
  • 必须设置了mItemAnimator
  • 下面的条件,是mDataSetHasChangedAfterLayout相关的。mDataSetHasChangedAfterLayout的意义是标记发生了数据变化,比如调用set或者swapAdapter。分析条件判断,我们发现发生变化后,必须满足hasStableIds。没有发生变化时,animationTypeSupported和mLayout.mRequestedSimpleAnimations必须满足其一。

关注下dispatchLayoutStep1的 mState.mInPreLayout = mState.mRunPredictiveAnimations的赋值,他表示在运行预测性动画时,此时在preLayout阶段。后面分析LayoutManger会用到。这个值在正常的测量时时false,只有在预测性动画测量阶段才会时true,在讲LayoutManager时会看到这个值产生的影响。

分析完条件判断,我们看下dispatchLayoutStep1中mRunSimpleAnimations为true时怎么处理的。

    int count = mChildHelper.getChildCount();
            for (int i = 0; i < count; ++i) {
                final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
                if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
                    continue;
                }
                final ItemHolderInfo animationInfo = mItemAnimator
                        .recordPreLayoutInformation(mState, holder,
                                ItemAnimator.buildAdapterChangeFlagsForAnimations(holder),
                                holder.getUnmodifiedPayloads());
                mViewInfoStore.addToPreLayout(holder, animationInfo);
                if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()
                        && !holder.shouldIgnore() && !holder.isInvalid()) {
                    long key = getChangedHolderKey(holder);
                    mViewInfoStore.addToOldChangeHolders(key, holder);
                }
            }

类ItemHolderInfo中封闭了对应ItemView的边界信息,left、top、right、bottom值。
对象mViewInfoStore的作用就是保存数据以供动画使用。

/**
 * Keeps data about views to be used for animations
 */
final ViewInfoStore mViewInfoStore = new ViewInfoStore();

后面mViewInfoStore.addToPreLayout方法存储进入

void addToPreLayout(RecyclerView.ViewHolder holder, RecyclerView.ItemAnimator.ItemHolderInfo info) {
        InfoRecord record = mLayoutHolderMap.get(holder);
        if (record == null) {
            record = InfoRecord.obtain();
            mLayoutHolderMap.put(holder, record);
        }
        record.preInfo = info;
        record.flags |= FLAG_PRE;
    }

放到了mLayoutHolderMap中,完成了存储。最后mState.mLayoutStep = State.STEP_LAYOUT,标记完成了设置了dispatchLayoutStep1方法。
dispatchLayoutStep1到这里就结束了。主要做动画的准备工作,存储一下现有item的信息。

dispatchLayoutStep2

dispatchLayoutStep2是真正进行测量的地方

    /**
     * 第二个布局步骤,我们对最终状态的视图进行实际布局。 如有必要,此步骤可能会运行多次(例如测量)。
     */
    private void dispatchLayoutStep2() {
        //祖传拦截和标记状态
        startInterceptRequestLayout();
        onEnterLayoutOrScroll();
        
        //断言判断
        mState.assertLayoutStep(State.STEP_LAYOUT | State.STEP_ANIMATIONS);
        mAdapterHelper.consumeUpdatesInOnePass();
        mState.mItemCount = mAdapter.getItemCount();
        mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;

        // Step 2: Run layout
        mState.mInPreLayout = false;
        mLayout.onLayoutChildren(mRecycler, mState);

        mState.mStructureChanged = false;
        mPendingSavedState = null;

        // onLayoutChildren may have caused client code to disable item animations; re-check
        mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;
        // 设置layout阶段状态
        mState.mLayoutStep = State.STEP_ANIMATIONS;
        
        onExitLayoutOrScroll();
        stopInterceptRequestLayout(false);
    }

看到dispatchLayoutStep2方法的主要工作是调用了mLayout.onLayoutChildren方法进行测量。LayoutManager的onLayoutChildren是一个空方法,系统提供的LayoutManager都实现了这个方法,下一篇这里我们着重分析下LinearLayoutManger的实现。这里实现了各个item的measure和layout。以支持RV的wrap_content。

最后设置 mState.mLayoutStep 为State.STEP_ANIMATIONS,标记已经执行完dispatchLayoutStep2步骤,需要执行dispatchLayoutStep3。

dispatchLayoutStep3

     //布局的最后一步,我们保存关于动画视图的信息,触发动画并进行任何必要的清理。
     private void dispatchLayoutStep3() {
        mState.assertLayoutStep(State.STEP_ANIMATIONS);
        startInterceptRequestLayout();
        onEnterLayoutOrScroll();
        //重制为标记位
        mState.mLayoutStep = State.STEP_START;
        if (mState.mRunSimpleAnimations) {
            //执行动画
            。。。
        }

        mLayout.removeAndRecycleScrapInt(mRecycler);
        mState.mPreviousLayoutItemCount = mState.mItemCount;
        mDataSetHasChangedAfterLayout = false;
        mDispatchItemsChangedEvent = false;
        mState.mRunSimpleAnimations = false;

        mState.mRunPredictiveAnimations = false;
        mLayout.mRequestedSimpleAnimations = false;
        if (mRecycler.mChangedScrap != null) {
            mRecycler.mChangedScrap.clear();
        }
        if (mLayout.mPrefetchMaxObservedInInitialPrefetch) {
            // Initial prefetch has expanded cache, so reset until next prefetch.
            // This prevents initial prefetches from expanding the cache permanently.
            mLayout.mPrefetchMaxCountObserved = 0;
            mLayout.mPrefetchMaxObservedInInitialPrefetch = false;
            mRecycler.updateViewCacheSize();
        }

        mLayout.onLayoutCompleted(mState);
        onExitLayoutOrScroll();
        stopInterceptRequestLayout(false);
        mViewInfoStore.clear();
        if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) {
            dispatchOnScrolled(0, 0);
        }
        recoverFocusFromState();
        resetFocusInfo();
    }

dispatchLayoutStep3内部主要做了一些状态的重制,并清空一些数据。到了第三部应该拿第一步存储的数据进行动画执行了,执行动画的方法在mState.mRunSimpleAnimations判断的内部。以后讲动画我们会细致的讲解。
相信通过测绘流程上下篇的讲解,大家对RecyclerView在View的基础上的测绘流程,应该有一定认识了。最终具体的测量就在LayoutManager中了。

下一篇会介绍LayoutManager,主要分析LinearLayoutManager,这个我们比较常用,并着重介绍onLayoutChildren方法。