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()来获得宽高。

本系列文章参考: 《android开发艺术探索》一书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值