AndroidX RecyclerView总结-测量布局

本文详细探讨了AndroidX RecyclerView的源码,从测量阶段到布局阶段,包括dispatchLayoutStep1、dispatchLayoutStep2和dispatchLayoutStep3。重点讲解了LinearLayoutManager的布局实现过程,阐述了如何寻找锚点、布局填充以及ViewHolder的添加和测量。通过对RecyclerView的深入理解,有助于优化Android应用的性能和用户体验。
摘要由CSDN通过智能技术生成

概述

通过博文记录RecyclerView的源码学习过程有助于巩固自己的记忆和加深整体实现机制的理解。

RecyclerView中通过Adapter将数据源各item转换成各ViewHolder和监听数据变化。ViewHolder顾名思义持有View,利用ViewHolder将item数据和持有的View进行绑定设置。RecyclerView对各item View的布局排列交由LayoutManager的子类处理,而在布局过程中,又会借助Recycler进行ViewHolder的缓存和复用,达到优化目的。RecyclerView还把item View的动画逻辑解耦至ItemAnimator。

RecyclerView架构

这里从RecyclerView的测量和布局过程入手,了解内部实现机制。

源码探究

文中源码基于 ‘androidx.recyclerview:recyclerview:1.1.0’

测量阶段

打开onMeasure方法:
[RecyclerView.java]

protected void onMeasure(int widthSpec, int heightSpec) {
   
    // mLayout为开发者设置的LayoutManager子类
    if (mLayout == null) {
   
        defaultOnMeasure(widthSpec, heightSpec);
        return;
    }
    // ···
}

首先判断如果未设置LayoutManager,则采用默认测量规则。

看一下defaultOnMeasure方法:
[RecyclerView.java]

void defaultOnMeasure(int widthSpec, int heightSpec) {
   
    // calling LayoutManager here is not pretty but that API is already public and it is better
    // than creating another method since this is internal.
    // chooseSize方法中判断SpecMode若为EXACTLY,则取SpecSize;若为AT_MOST,则取
    // max(SpecSize, min(Padding和, MinimumWidth));否则取max(Padding和, MinimumWidth)
    final int width = LayoutManager.chooseSize(widthSpec,
            getPaddingLeft() + getPaddingRight(),
            ViewCompat.getMinimumWidth(this));
    final int height = LayoutManager.chooseSize(heightSpec,
            getPaddingTop() + getPaddingBottom(),
            ViewCompat.getMinimumHeight(this));

    // 设置RecyclerView的尺寸
    setMeasuredDimension(width, height);
}

默认规则会以父容器给定的SpecSize或RecyclerView的Padding与MinimumWidth来计算尺寸。

回到onMeasure方法中:
[RecyclerView.java]

protected void onMeasure(int widthSpec, int heightSpec) {
   
    // ···
    // 判断LayoutManager是否启用自动测量,isAutoMeasureEnabled默认返回false,但是
    // 通常LayoutManager需要重写该方法以返回true,例如LinearLayoutManager、StaggeredGridLayoutManager。
    if (mLayout.isAutoMeasureEnabled()) {
   
        // ···
    } else {
   
        // ···
        // onMeasure方法中默认有调用了RecyclerView的defaultOnMeasure方法
        mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
        // ···
    }
}

判断自定义LayoutManager是否重写isAutoMeasureEnabled以返回true。若返回false,则会执行RecyclerView默认测量规则。

继续看onMeasure中isAutoMeasureEnabled为true的流程部分:
[RecyclerView.java]

protected void onMeasure(int widthSpec, int heightSpec) {
   
    // ···
    if (mLayout.isAutoMeasureEnabled()) {
   
        final int widthMode = MeasureSpec.getMode(widthSpec);
        final int heightMode = MeasureSpec.getMode(heightSpec);

        /**
         * This specific call should be considered deprecated and replaced with
         * {@link #defaultOnMeasure(int, int)}. It can't actually be replaced as it could
         * break existing third party code but all documentation directs developers to not
         * override {@link LayoutManager#onMeasure(int, int)} when
         * {@link LayoutManager#isAutoMeasureEnabled()} returns true.
         */
        // 按照默认规则设置一次尺寸(当SpecMode非EXACTLY且数据源不为空时,尺寸未必准确)
        mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);

        final boolean measureSpecModeIsExactly =
                widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY;
        // 当指定尺寸是明确的或还没有设置数据源时,默认规则设置的尺寸满足,结束测量阶段
        if (measureSpecModeIsExactly || mAdapter == null) {
   
            return;
        }

        // mLayoutStep初始状态为STEP_START
        if (mState.mLayoutStep == State.STEP_START) {
   
            // 执行第一阶段布局---【1】
            dispatchLayoutStep1();
        }
        // set dimensions in 2nd step. Pre-layout should happen with old dimensions for
        // consistency
        // 从Spec中获取size和mode,赋值给对应mWidth、mWidthMode、mHeight、mHeightMode成员。
        // 当mode为UNSPECIFIED时,若API版本低于23,会将对应对应mWidth、mHeight设为0。
        mLayout.setMeasureSpecs(widthSpec, heightSpec);
        // mIsMeasuring用于标记RecyclerView当前正在计算布局边界
        mState.mIsMeasuring = true;
        // 执行第二阶段布局---【2】(在该阶段中会对child进行测量)
        dispatchLayoutStep2();

        // now we can get the width and height from the children.
        // 遍历child,计算child布局边界(包含分隔线),设置RecyclerView自身尺寸
        mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);

        // if RecyclerView has non-exact width and height and if there is at least one child
        // which also has non-exact width & height, we have to re-measure.
        // 判断是否需要二次测量,shouldMeasureTwice默认返回false。
        // 自定义LayoutManager可根据自身布局特性重写该方法,当宽高SpecMode都非EXACTLY且有一个child的宽高尺寸也都不是EXACTLY时需要返回true。
        if (mLayout.shouldMeasureTwice()) {
   
            mLayout.setMeasureSpecs(
                    MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
            mState.mIsMeasuring = true;
            dispatchLayoutStep2();
            // now we can get the width and height from the children.
            mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);
        }
    } else {
   
        // ···
    }
}

可以看到,RecyclerView在测量阶段若启用AutoMeasure就会开始进行一部分布局操作(dispatchLayoutStep1、dispatchLayoutStep2)。

布局分三个阶段,分别对应dispatchLayoutStep1dispatchLayoutStep2dispatchLayoutStep3三个方法。

mState实例为State,用于保存当前RecyclerView状态的有用信息,例如目标滚动位置或视图焦点,还可以保留由资源ID标识的任意数据。它的mLayoutStep用于标记当前布局阶段状态,初始状态为STEP_START,执行dispatchLayoutStep1方法后变更为STEP_LAYOUT,执行dispatchLayoutStep2后变为STEP_ANIMATIONS,执行dispatchLayoutStep3后又变回STEP_START

布局阶段

进入RecyclerView的onLayout方法:
[RecyclerView.java]

protected void onLayout(boolean changed, int l, int t, int r, int b) {
   
    TraceCompat.beginSection(TRACE_ON_LAYOUT_TAG);
    // 派发布局流程
    dispatchLayout();
    TraceCompat.endSection();
    // 标记首次布局完成
    mFirstLayoutComplete = true;
}
dispatchLayout

接着进入dispatchLayout方法:
[RecyclerView.java]

void dispatchLayout() {
   
    if (mAdapter == null) {
   
        Log.e(TAG, "No adapter attached; skipping layout");
        // leave the state in START
        return;
    }
    if (mLayout == null) {
   
        Log.e(TAG, "No layout manager attached; skipping layout");
        // leave the state in START
        return;
    }
    mState.mIsMeasuring = false;
    // 判断布局阶段状态(onMeasure中有可能先执行dispatchLayoutStep1、dispatchLayoutStep2)
    if (mState.mLayoutStep == State.STEP_START) {
   
        // 若测量阶段未进行任何布局操作,则从阶段一开始执行
        dispatchLayoutStep1();
        // 将生成EXACTLY的MeasureSpec,并调用setMeasureSpecs传入
        mLayout.setExactMeasureSpecsFrom(this);
        // 执行布局阶段二
        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.
        // 若有item的变更或尺寸变化,则再执行一次布局阶段二
        mLayout.setExactMeasureSpecsFrom(this);
        dispatchLayoutStep2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值