View的measure过程

了解measure过程之前,要先了解一下MeasureSpec和LayoutParams的概念,因为View的大小是由其共同决定的。

MeasureSpec简介

MeasureSpec:测量说明书(测量规格),MeasureSpec在很大成功度上决定了一个View的尺寸规格。(View的尺寸规格还受父容器的影响,因为父容器影响View的MeasureSpec的创建过程)

MeasureSpec概念

MeasureSpec代表一个32位的int值,高2位代表SpecMode,低30位代表SpecSize,SpecMode是指测量模式,SpecSize指在该测量模式下的规格大小。

MeasureSpec工作原理

MeasureSpec通过将SpecMode和SpecSize打包成一个int值来避免过多的对象内存分配,为了方便操作,其提供了打包和解包的方法。SpecMode和SpecSize也是一个int值,一组SpecMode和SpecSize可以打包成一个MeasureSpec,而一个MeasureSpec可以通过解包的形式得出其原始的SpecMode和SpecSize。
简单说:
MeasureSpec的值由specSize和specMode共同组成的,其中specSize记录的是大小,specMode记录的是规格。

SpecMode三种模式
  • UNSPECIFIED
    父容器不对View有任何限制,要多大给多大,这种情况一般用于系统内部,表示一种测量状态。
  • EXACTLY
    父容器已经检测出View所需的精确大小,这个时候View的最终大小就是SpecSize所指定的值。它对应于LayoutParams中match_parent和具体的数值这两种模式。
  • AT_MOST
    父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体值要看View的具体实现。它对应于LayoutParams中wrap_content。

MeasureSpec和LayoutParams的关系

系统内部是通过MeasureSpec来进行View的测量,对于普通的View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams来共同决定的,那么针对不同的父容器和View本身不同的LayoutParams,View就可以有多种MeasureSpec。
当View采用固定宽高的时候,不管父容器的MeasureSpec是什么,View的MeasureSpec都是精确模式并且其大小遵循Layoutparams中的大小。

measure过程

1、View的measure过程

View的measure过程由其measure方法来完成,measure方法是一个final类型的方法,因此不能重写此方法,在View的measure方法中会去调用View的onMeasure方法,因此只需要看onMeasure的实现,View的onMeasure方法如下:

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

setMeasuredDimension()方法是设置View的宽高测量值的,我们来看下getDefaultSize方法,如何获得宽高的

   /**
     * Utility to return a default size. Uses the supplied size if the
     * MeasureSpec imposed no constraints. Will get larger if allowed
     * by the MeasureSpec.
     *
     * @param size Default size for this view
     * @param measureSpec Constraints imposed by the parent
     * @return The size this view should be.
     */
    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;
    }

先来看一下AT_MOSTEXACTLY这两种情况,很明显getDefaultSize返回的大小就是measureSpec中的specSize,而这个specSize就是View测量后的大小。
UNSPECIFIED这种情况,一般用于系统内部的测量过程,此时View的大小就是getDefaultSize返回的第一个参数size,即宽高分别为getSuggestedMinimumWidth(),getSuggestedMinimumHeight()这两个方法的返回值。

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

protected int getSuggestedMinimumHeight() {
        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());

    }

从上面getSuggestedMinimumWidth的代码可以看出(getSuggestedMinimumHeight原理也一样),如果View没有设置背景,那么View的宽度为mMinWidth ,mMinWidth的值为android:minWidth这个属性所指定的值,如果android:minWidth属性没有指定值,那么mMinWidth 则默认为0;如果View指定了背景,则View的宽度为max(mMinWidth, mBackground.getMinimumWidth())
mBackground.getMinimumWidth()又是什么?

  public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

getMinimumWidth返回的就是Drawable的原始宽度,如果这个Drawable没有原始宽度则返回0。(例:ShapeDrawable无原始高度,而BitmapDrawable有原始宽高)。

从getDefaultSize方法的实现来看,View的宽高由specSize决定,所以可以得出结论:直接继承View的自定义控件需要重写onMeasure方法并设置wrap_content时的自身大小,否则再布局中使用wrap_content就相当于match_parent。因为View在布局中使用wrap_conten,那么它的specMode是AT_MOST模式,在这种模式下它的宽高等于specSize;这种情况下的specSize是parentSize,而parentSize是父容器中目前可用大小,也就是父容器当前剩余空间大小,这种效果和在布局中使用match_parent效果一致。如何解决这个问题?代码如下:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode
                ==MeasureSpec.AT_MOST){
            setMeasuredDimension(mWidth,mHeight);
        }else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(mWidth,heightSpecSize);
        }else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize,mHeight);
        }
    }

2. ViewGroup的measure

对于ViewGroup来说,除了完成自己的measure外,还会遍历调用所有子元素的measure方法,各个子元素在递归去执行这个过程,ViewGroup是一个抽象类,因此它没有重写View的onMeasure方法,而是提供了measureChildren方法。
measureChildren代码

/**
     * Ask all of the children of this view to measure themselves, taking into
     * account both the MeasureSpec requirements for this view and its padding.
     * We skip children that are in the GONE state The heavy lifting is done in
     * getChildMeasureSpec.
     *
     * @param widthMeasureSpec The width requirements for this view
     * @param heightMeasureSpec The height requirements for this view
     */
    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);
            }
        }
    }

从上面代码可以看出,measureChildren方法会遍历所有 的子View,如果View的状态不是GONE就调用measureChild去进行下一步测量
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);
    }

measureChild的思想就是取出子元素的LayoutParams,然后再通过getChildMeasureSpec来创建子元素的MeasureSpec,接着将MeasureSpec直接传递给View的measure方法进行测量。

因为ViewGroup是抽象类,没有onMeasure方法,所以只能通过它的子类onMeasure方法来分析ViewGroup的measure过程。

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

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    for (int i = 0; i < count; ++i) {
              final View child = getVirtualChildAt(i);
              ...
               measureChildBeforeLayout(
                       child, i, widthMeasureSpec, 0, heightMeasureSpec,
                       totalWeight == 0 ? mTotalLength : 0);
               if (oldHeight != Integer.MIN_VALUE) {
                   lp.height = oldHeight;
                }

                final int childHeight = child.getMeasuredHeight();
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
                       lp.bottomMargin + getNextLocationOffset(child));
    }
}

从上面的代码可以看出,系统会遍历子元素并对每个子元素执行measureChildBeforeLayout方法,这个方法内部会调用子元素的measure方法,这样各个子元素就开始依次进入measure过程,并且系统会通过mTotalLength 这个变量来存储LinearLayout在竖直方向上的初步高度。每测量一个子元素,mTotalLength就会增加,增加的部分主要包括了子元素的高度以及子元素在竖直方向上的margin等。当子元素测量完毕后,LinearLayout会测量自己的大小。
View的measure过程是三大流程中最复杂的一个,measure完成以后,通过getMeasuredWidth/Height方法就可以正确的获取View的测量宽高了。
现在我们来获取Textview的宽高:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.tv);
        Log.e("tag", "========  onCreate " + mTextView.getMeasuredWidth() + "  " + mTextView.getMeasuredHeight());
    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.e("tag", "========  onStart " + mTextView.getMeasuredWidth() + "  " + mTextView.getMeasuredHeight());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("tag", "========  onResume " + mTextView.getMeasuredWidth() + "  " + mTextView.getMeasuredHeight());
    }

Log日志

11-29 15:32:43.578 12034-12034/? E/tag: ========  onCreate 0  0
11-29 15:32:43.579 12034-12034/? E/tag: ========  onStart 0  0
11-29 15:32:43.581 12034-12034/? E/tag: ========  onResume 0  0

发现在Activity声明周期里并没有获得TextView的宽高。这是因为View的measure过程和Activity的生命周期方法不是同步执行的,因此无法保证Activity执行了onCreate ,onStart ,onResume 时View已经测量完毕,如果View没有测量完毕,那么宽高就是0。下面给出几种方法来解决这个问题:
1、 Activity/View onWindowFocusChanged()方法
onWindowFocusChanged方法的含义:View已经初始化完成了,宽高已经准备好了,这时候就可以去获取宽高了。

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus)
            Log.e("tag", "========  onWindowFocusChanged " + mTextView.getMeasuredWidth() + "  " + mTextView.getMeasuredHeight());
    }
    
    Log日志:
    E/tag: ========  onWindowFocusChanged 225  57

2、 view.post(runnable)
通过post可以将一个runnable投递到消息队列的尾部,然后等待Looper调用此runnable的时候,View也已经初始化好了。

 mTextView.post(new Runnable() {
            @Override
            public void run() {
                Log.e("tag", "========  post " + mTextView.getMeasuredWidth() + "  " + mTextView.getMeasuredHeight());
            }
        });

Log日志:
E/tag: ========  post 225  57

还可以通过ViewTreeObserver类的回调方法和view.measure()来获得宽高。

本文ca

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

推荐阅读更多精彩内容