Android——View的工作流程——ViewGroup的measure过程

一、measure 过程

对 ViewGroup 来说,除了完成自己的 measure 过程以外,还要遍历所有子 View 的 measure 方法,各个子元素再去递归执行这个过程。

ViewGroup 的 measure 过程代码调用顺序如下:

measure 过程

1. measure()

Android 源码中,View 类的声明是

public class View implements Drawable.Callback, KeyEvent.Callback,
    AccessibilityEventSource{}

ViewGroup 类的声明是

public abstract class ViewGroup extends View implements ViewParent, ViewManager {}

ViewGroup 类是 View 类的子类,ViewGroup 的 measure 过程入口是 View 类中的measure()方法,与单一 View 的测量过程中介绍的measure()方法一致。

/**
 * 源码分析:measure()
 * 作用:基本测量逻辑的判断;调用onMeasure()
 * 注:与单一View measure过程中讲的measure()一致
 **/
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    ...
    int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : mMeasureCache.indexOfKey(key);
    if (cacheIndex < 0 || sIgnoreMeasureCache) {

        // 调用onMeasure()计算视图大小
        onMeasure(widthMeasureSpec, heightMeasureSpec);
        mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
    } else {
        ...
    }
}

2. onMeasure()

ViewGroup 是一个抽象类,它没有重写 View 的 onMeasure()方法,该方法作用是父容器测量子 View 的尺寸,其测量过程的onMeasure()方法需要各个子类去具体实现。

Q:为什么 ViewGroup 的 measure 过程不像单一 View 的 measure 过程那样对 onMeasure() 做统一的实现?

A:因为不同的 ViewGroup 子类(LinearLayout、RelativeLayout 及自定义的 ViewGroup 子类等)具备不同的布局特性,这导致他们的测量细节各有不同,ViewGroup 无法对onMeasure()做统一实现。

在自定义 ViewGroup 中,关键在于:根据需求复写onMeasure()从而实现你的子View测量逻辑。复写onMeasure()的套路如下:

/**
 * 根据自身测量逻辑复写onMeasure(),分3步:
 * (1)遍历所有子view,依次进行测量
 * (2)合并所有子View的尺寸大小,最终得到ViewGroup父视图的测量值(自身实现)
 * (3)存储测量后View宽/高值,调用setMeasuredDimension()
 * @param widthMeasureSpec
 * @param heightMeasureSpec
 */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // 定义存放测量后view宽/高的变量
    int widthMeasure;
    int heightMeasure;

    // 1,遍历所有子View,依次进行测量
    measureChildren(widthMeasureSpec, heightMeasureSpec);

    // 2,合并所有子View的尺寸大小,最终得到父视图的测量值
    void measureCarson {
        // 自己实现
    }

    // 3,存储测量后view的宽/高
    setMeasuredDimension(widthMeasure, heightMeasure);

}

下面看下 LinearLayout 类中实现的onMeasure()方法。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (mOrientation == VERTICAL) {
        measureVertical(widthMeasureSpec, heightMeasureSpec);
    } else {
        measureHorizontal(widthMeasureSpec, heightMeasureSpec);
    }
}

measureVertical()measureHorizontal()原理类似,我们以前者为例,代码主要分三个步骤:

① 遍历所有子View ,依次进行测量
系统首先遍历子元素,并对每个子元素执行measureChildBeforeLayout()方法,这个方法内部会调用子元素的measure()方法,这样各个元素就开始进入 measure 过程

② 合并所有子View的尺寸大小,得到 ViewGroup 的测量值
系统通过mTotalLength存储 LinearLayout 在竖直方向上的高度

③ 存储 ViewGroup 的测量值
使用setMeasuredDimension()方法

/**
 * 测量 LinearLayout 垂直方向的测量尺寸
 *
 * @param widthMeasureSpec  父容器的宽测量规格
 * @param heightMeasureSpec 父容器的高测量规格
 */
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    final int count = getVirtualChildCount();

    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

    // 对于每一个垂直方向上的子View
    /**
     *  步骤1:遍历所有子View ,依次进行测量
     *  注:该方法内部,最终会调用measureChildren(),从而遍历所有子View & 测量
     **/
    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            mTotalLength += measureNullChild(i);
            continue;
        }
        // 若子View不可见,则直接跳过该View的测量过程
        // 注:若可见属性设置为VIEW.INVISIBLE,则仍需测量
        if (child.getVisibility() == View.GONE) {
            i += getChildrenSkipCount(child, i);
            continue;
        }

        final LayoutParams lp = (LayoutParams) child.getLayoutParams();

        totalWeight += lp.weight;

        final boolean useExcessSpace = lp.height == 0 && lp.weight > 0;
        if (heightMode == MeasureSpec.EXACTLY && useExcessSpace) {
            // 如果LinearLayout的specMode为EXACTLY且子View设置了weight属性,在这里会跳过子View的measure过程
            // 同时标记skippedMeasure属性为true,后面会根据该属性决定是否进行第二次measure
            // 若LinearLayout的子View设置了weight,会进行两次measure计算,比较耗时
            // 这就是为什么LinearLayout的子View需要使用weight属性时候,最好替换成RelativeLayout布局
            final int totalLength = mTotalLength;
            mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
            skippedMeasure = true;
        } else {
            if (useExcessSpace) {
                // The heightMode is either UNSPECIFIED or AT_MOST, and
                // this child is only laid out using excess space. Measure
                // using WRAP_CONTENT so that we can find out the view's
                // optimal height. We'll restore the original height of 0
                // after measurement.
                lp.height = LayoutParams.WRAP_CONTENT;
            }

            /**
             * 调用measureChildBeforeLayout()测量子View
             */
            final int usedHeight = totalWeight == 0 ? mTotalLength : 0;
            measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
                heightMeasureSpec, usedHeight);

            /**
             * 通过 getMeasuredHeight() 获取View的测量宽/高
             * 注:在某些极端情况下,系统可能需要多次 measure 才能确定最终的宽/高,在这种情形下,
             * 在onMeasure()中通过 getMeasuredHeight() 获取测量宽高是不准确的。
             * 一个好的习惯是,在 onLayout() 方法中获取 View 的最终宽/高
             */
            final int childHeight = child.getMeasuredHeight();
            if (useExcessSpace) {
                // Restore the original height and record how much space
                // we've allocated to excess-only children so that we can
                // match the behavior of EXACTLY measurement.
                lp.height = 0;
                consumedExcessSpace += childHeight;
            }

            // totalLength
            /**
             * 系统通过 mTotalLength 这个变量来存储 LinearLayout 在竖直方向的初步高度。
             * 每测量一个元素, mTotalLength就会增加,增加的部分主要包括了子元素的高度以及子元素在竖直方向上的 margin 等。
             */
            final int totalLength = mTotalLength;
            mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
                lp.bottomMargin + getNextLocationOffset(child));


        }
    }

    /**
     *  步骤2:合并所有子View的尺寸大小,最终得到ViewGroup的测量值
     *  子元素测量完毕后,LinearLayout 根据子元素的情况来测量自己的大小。
     **/
    // 记录 LinearLayout 占用的总高度,除了子View占用的高度,还有本身的 padding 属性
    // Add in our padding
    mTotalLength += mPaddingTop + mPaddingBottom;

    int heightSize = mTotalLength;

    // Check against our minimum height
    heightSize = Math.max(heightSize, getSuggestedMinimumHeight());

    // Reconcile our calculated size with the heightMeasureSpec
    int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
    heightSize = heightSizeAndState & MEASURED_SIZE_MASK;

    /**
     *  步骤3:存储测量后View宽/高的值:调用setMeasuredDimension()
     **/
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
        heightSizeAndState);
}

3. measureChildren()

ViewGroup 类中的方法。在该方法中遍历父容器中的所有子元素,逐个进行 measure。

/**
 * 遍历,测量父容器中的所有子View
 *
 * @param widthMeasureSpec 父容器的宽测量规格
 * @param heightMeasureSpec 父容器的高测量规格
 */
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
    final int size = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < size; ++i) {
        final View child = children[i];
        if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
            // 调用measureChild()方法对子View进行进一步测量
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}

4. measureChild()

ViewGroup 类中的方法。该方法测量某一具体的子元素,测量过程参见自定义View——单一View的measure过程

/**
 * 计算子View的MeasureSpec,并且测量子View最终的宽/高
 *
 * @param child The child to measure
 * @param parentWidthMeasureSpec The width requirements for this view
 * @param parentHeightMeasureSpec The height requirements for this view
 */
protected void measureChild(View child, int parentWidthMeasureSpec,
    int parentHeightMeasureSpec) {
    // 子View自身的布局参数
    final LayoutParams lp = child.getLayoutParams();

    // 计算子View的测量规格
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
        mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
        mPaddingTop + mPaddingBottom, lp.height);
    // 根据上述参数测量子View
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

二、重点说明

参考文献

自定义View Measure过程 - 最易懂的自定义View原理系列(2)
任玉刚_Android开发艺术探索

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