View的工作流程-measure过程

前言

上一篇文章深入理解MeasureSpec我们分析了View的测量规格,根据MeasureSpec才能测量出View的大小,下面我们详细分析一下View的测量过程-measure过程,measure过程主要是测量出View的宽/高,其实View的测量分为两种情况,一是直接继承View的,通过OnMeasure()过程测量自己就可以了,还有一种是继承自ViewGroup的,除了测量自身外,还要遍历去测量所有子View,子View在依次执行测量过程。

View的measure过程

View的measure过程是从ViewRootImplperformMeasure()开始的,performMeasure() 里面会调用Viewmeasure()方法,而Viewmeasure()是用final修饰的,意味着子类不能重写该方法,但是在Viewmeasure()方法里面会去调用我们熟悉的onMeasure()方法,也就是开始了View的测量过程,下面我们看下ViewonMeasure()方法

View#onMeasure()

     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

我们发现这里面逻辑很简洁,就是调用setMeasuredDimension()方法,也就说当我们自定义一个View重写onMeasure()时,必须调用setMeasuredDimension()方法,这个方法会存储View的测量值,我们看下参数里的getDefaultSize()方法

View#getDefaultSize()

    public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

这里逻辑也很好理解,我们只需要看MeasureSpec.AT_MOSTMeasureSpec.EXACTLY这两种情况,getDefaultSize()返回的大小就是测量后的大小,对于MeasureSpec.UNSPECIFIED这种模式,一般用于系统内部的测量过程,View的大小是系统的建议值,也就是getDefaultSize()的第一个参数getSuggestedMinimumHeight()的返回值,宽高同理

View#getSuggestedMinimumWidth()

    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

我们发现就是根据View是否设置背景进行判断的,如果没设置背景就返回mMinWidth,设置背景看就返回mMinWidth和背景宽度的最大值,mMinWidth对应于android:minWidth,如果不指定默认为0;我们再看下mBackground.getMinimumWidth()的含义,在View的全局变量里我们看到private Drawable mBackground;背景就是一个Drawable,再看下getMinimumWidth()

Drawable#getMinimumWidth()

     * @return The minimum width suggested by this Drawable. If this Drawable
     *         doesn't have a suggested minimum width, 0 is returned.
     */
    public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

我们看到注释没如果没设置背景就返回0,否则就返回背景的原始宽度,这个原始宽度又是什么呢,例如在xml中定义shape填充这种纯色,原始宽度就为0,如果设置BitmapDrawable为背景,原始宽度就不为0.通过以上可以看出getSuggestedMinimumWidth()返回的就是View在MeasureSpec.UNSPECIFIED这种模式下测量的大小。以上就是我们分析普通View的onMeasure过程。

ViewGroup的measure过程

ViewGroup是继承与View的,它是一个抽象类没有重写onMeasure方法,但是有一个measureChildren()方法,通过名字我们也能猜到就是测量子View的方法,下面我们详细看下

ViewGroup#measureChildren()

    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(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

这里就是通过遍历所有的子View并且不是GONE的情况下去执行measureChild()方法,这也很好的解释了为什么我在将某个View设置GONE后,不占用空间的原因,因为根本就没有去测量,我们再看下measureChild()方法

ViewGroup#measureChild()

    protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

这里逻辑也很简单,首先取出子ViewLayoutParams,将父控件的MeasureSpecLayoutParams作为参数传到getChildMeasureSpec()方法中来创建子ViewMeasureSpecgetChildMeasureSpec()这个方法在上一篇深入理解MeasureSpec中已经详细的介绍,请自行查看!子View调用 measure方法,里面会执行View的onMeasure()方法,下面我们看下FrameLayout的测量过程。

FrameLayout#onMeasure()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();
    //判断当前布局的宽高是否为EXACTLY模式
    final boolean measureMatchParentChildren =
            MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
            MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
    mMatchParentChildren.clear();

    int maxHeight = 0;
    int maxWidth = 0;
    int childState = 0;

     for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
            //对每一个子View进行测量
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            //寻找子View中宽高的最大者,因为如果FrameLayout是wrap_content属性
            //那么它的大小取决于子View中的最大者
            maxWidth = Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
            maxHeight = Math.max(maxHeight,
                    child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
            childState = combineMeasuredStates(childState, child.getMeasuredState());
            //如果FrameLayout非EXACTLY模式,添加到mMatchParentChildren中
            if (measureMatchParentChildren) {
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

   ...

    //保存测量结果
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));

    //子View中设置为match_parent的个数
    count = mMatchParentChildren.size();
    if (count > 1) {
        for (int i = 0; i < count; i++) {
            final View child = mMatchParentChildren.get(i);
            final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            //对FrameLayout的宽度规格设置,因为这会影响子View的测量
            final int childWidthMeasureSpec;
            if (lp.width == LayoutParams.MATCH_PARENT) {
                final int width = Math.max(0, getMeasuredWidth()
                        - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                        - lp.leftMargin - lp.rightMargin);
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        width, MeasureSpec.EXACTLY);
            } else {
                childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                        getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                        lp.leftMargin + lp.rightMargin,
                        lp.width);
            }
            ...
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}

首先,FrameLayout根据它的MeasureSpec来对每一个不为GONE的子View进行测量,即调用measureChildWithMargin()方法,measureChildWithMargin()这个方法和measureChild()类似,多计算了边距,再对每一个子View进行测量,之后会寻找其中最大的宽高,那么FrameLayout的测量宽高会受到这个子View的最大宽高的影响(wrap_content模式),接着调用setMeasureDimension方法,把FrameLayout的测量宽高保存。最后则是特殊情况的处理,即当FrameLayout为wrap_content属性时,如果其子View是match_parent属性的话,则要重新设置FrameLayout的测量规格,然后重新对该部分View测量。

总结

上面我们已经分析了ViewMeasure过程,测量控件大小是父控件发起的
父控件要测量子控件大小,需要重写onMeasure()方法,然后调用measureChildren()或者measureChildWithMargins()方法
测量控件的步骤:
父控件onMeasure->measureChildren/measureChildWithMargin->getChildMeasureSpec->
子控件的measure->onMeasure->setMeasureDimension->
父控件onMeasure结束调用setMeasureDimension最后保存自己的大小.

推荐

深入理解MeasureSpec

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

推荐阅读更多精彩内容