View的Measure

Android开发艺术探索笔记

SpecMode
  1. UNSPECIFIED,表示一种测量状态,对View的大小不做限制,要多大给多大。一般用于系统内部。
  2. EXACTLY,父容器已经知道View的精确大小,即SpecSize。对应于LayoutParams的match_parent。
  3. AT_MOST,父容器指定了一个最大的SpecSize,View不能大于该值,View具体的大小要看View的具体实现。对应于LayoutParams的wrap_content。
整体Measure流程

主要是分为MeasureSpec和Measure两个过程

  1. MeasureSpec过程是根据View自身的LayoutParams和其父控件的MeasureSpec来确定View的MeasureSpec。顶级父控件DecorView的MeasureSpec由窗口的尺寸和自身的LayoutParams决定。
  2. Measure过程是根据View的MeasureSpec来测量的宽/高度(View的最终宽高和四个顶点的位置在layout结束后确定)。
MeasureSpec的过程

分为顶层View即DecorView,和普通View(包含ViewGroup)两种情况:
. DecorView,其MeasureSpec由窗口的尺寸和自身的LayoutParams决定。
. 普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同决定。

  1. DecorView的MeasureSpec的创建过程
    DecorView对应的实现类是ViewRootImpl。MeasureSpec从measureHierarchy方法开始。
    先码上measureHierarchy的所有代码,看看就好:
if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            // On large screens, we don't want to allow dialogs to just
            // stretch to fill the entire width of the screen to display
            // one line of text.  First try doing the layout at a smaller
            // size to see if it will fit.
            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
            int baseSize = 0;
            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
                baseSize = (int)mTmpValue.getDimension(packageMetrics);
            }
            if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
            if (baseSize != 0 && desiredWindowWidth > baseSize) {
                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
                    goodMeasure = true;
                } else {
                    // Didn't fit in that size... try expanding a bit.
                    baseSize = (baseSize+desiredWindowWidth)/2;
                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
                            + baseSize);
                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
                        if (DEBUG_DIALOG) Log.v(TAG, "Good!");
                        goodMeasure = true;
                    }
                }
            }
        }

measureHierarchy()中的参数:desiredWindowWidth窗口的宽 ;desiredWindowHeight窗口的高
measureHierarchy会处理WRAP_CONTENT时的大屏的特殊情况,见如下的注释

if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            // On large screens, we don't want to allow dialogs to just
            // stretch to fill the entire width of the screen to display
            // one line of text.  First try doing the layout at a smaller
            // size to see if it will fit.

measureHierarchy中大部分代码都是用来处理这个逻辑的。剩下关于MeasureSpec的代码只有短短三行

 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

MeasureSpec的逻辑重点自然在getRootMeasureSpec()方法中。其注释就直白的说明了

 /**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     * 根据root view的 layout params确定其measure spec
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            //对应MeasureSpec.EXACTLY的精确模式,大小为窗口大小。
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            //对应MeasureSpec.AT_MOST的最大模式,大小不能超过窗口大小。
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            //对应MeasureSpec.EXACTLY的精确模式,大小为布局中的指定大小
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }
  1. 普通View的MeasureSpec的创建过程
    View的measure的ViewGroup的measureChildWithMargins开始
   /**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding
     * and margins. The child must have MarginLayoutParams The heavy lifting is
     * done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param widthUsed Extra space that has been used up by the parent
     *        horizontally (possibly by other children of the parent)
     * @param parentHeightMeasureSpec The height requirements for this view
     * @param heightUsed Extra space that has been used up by the parent
     *        vertically (possibly by other children of the parent)
     */
    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

又上面代码可以看出MeasureSpec的逻辑代码自然是在getChildMeasureSpec()中。也可以看出,在确定好MeasureSpec后,就开始了child的measure流程
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
下面看getChildMeasureSpec的具体逻辑

 /**
     * Does the hard part of measureChildren: figuring out the MeasureSpec to
     * pass to a particular child. This method figures out the right MeasureSpec
     * for one dimension (height or width) of one child view.
     *
     * The goal is to combine information from our MeasureSpec with the
     * LayoutParams of the child to get the best possible results. For example,
     * if the this view knows its size (because its MeasureSpec has a mode of
     * EXACTLY), and the child has indicated in its LayoutParams that it wants
     * to be the same size as the parent, the parent should ask the child to
     * layout given an exact size.
     *
     * @param spec The requirements for this view
     * @param padding The padding of this view for the current dimension and
     *        margins, if applicable
     * @param childDimension How big the child wants to be in the current
     *        dimension
     * @return a MeasureSpec integer for the child
     */
    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);
       //首先说下padding参数,以宽度为例。由measureChildWithMargins方法看出,该参数是将ViewGroup的 
       //左右padding,view自身的左右margin以及ViewGroup中已经被占用的宽度。由此可以看出,
       //无论view怎样,其宽度都不能超过lp.width - padding

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY: //父控件为精确模式EXACTLY时
            if (childDimension >= 0) {            //1. 1View布局中为具体大小值
                resultSize = childDimension;  // view为EXACTLY,大小为布局中指定的值
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) { //1.2 View为MATCH_PARENT
                // Child wants to be our size. So be it.
                resultSize = size;             //View可以精确到和父控件一样大,所以View为EXACTLY模式
                resultMode = MeasureSpec.EXACTLY;  //大小为父控件可用的大小(除掉了padding)
            } else if (childDimension == LayoutParams.WRAP_CONTENT) { //1.3 View为WRAP_CONTENT
                // Child wants to determine its own size. It can't be
                // bigger than us.  //此时View大小随内容变化,但不能超过父控件的可用空间
                resultSize = size; //所以View为AT_MOST最大模式
                resultMode = MeasureSpec.AT_MOST; //大小为父控件可用的大小(除掉了padding)
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:  //父控件为AT_MOST最大模式
            if (childDimension >= 0) {  //2.1 View布局中为具体大小值
                // Child wants a specific size... so be it
                resultSize = childDimension; // view为EXACTLY,大小为布局中指定的值
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//2.2View为MATCH_PARENT
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size; //View大小和父控件一样,不能超过父控件的最大值
                resultMode = MeasureSpec.AT_MOST; //View为最大模式,大小不能超过父控件的可用空间
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//2.3 View为WRAP_CONTENT
                // Child wants to determine its own size. It can't be
                // bigger than us. //View大小随内容变化,打不能超过超过父控件的可用空间
                resultSize = size;  //所以View为AT_MOST最大模式
                resultMode = MeasureSpec.AT_MOST;  //大小为父控件可用的大小(除掉了padding)
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED: //父控件为UNSPECIFIED未指定模式
            if (childDimension >= 0) { //3.1View布局中为具体大小值
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY; // view为EXACTLY,大小为布局中指定的值
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//3.2View为MATCH_PARENT
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED; //View也为UNSPECIFIED,大小为0
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//3.3View为WRAP_CONTENT
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;//View也为UNSPECIFIED,大小为0
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }
measure流程

分为View的measure过程和ViewGroup的measure过程。

  1. View的measure过程
    ViewGroup在measureChildWithMargins中确定了View的MeasureSpec后调用
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

View的measure方法是个final方法,但其中会调用onMeasure();

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } 
...
}

View的onMeasure方法如下:

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

setMeasuredDimension()方法会设置View的宽高,如果我们在重写onMeasure时,也一定要该方法,是宽高生效。
默认的宽高逻辑代码在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_MOST和 MeasureSpec.EXACTLY模式时,View的大小即specSize。
MeasureSpec.UNSPECIFIED时View的大小为第一个参数(以宽为例),即onMeasure传过来的getSuggestedMinimumWidth。

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

这里的逻辑是,如果View没有设置背景,则去mMinWidth,对应的是android:minWidth设置的值;如果View设置了背景,怎取背景的getMinimumWidth()值和minWidth中大的那个.
背景的getMinimumWidth()也很简单,即有原始宽高时取原始宽高,没有取0.

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

总结,View的测量问题在于:View在WRAP_CONTENT时,其最终的模式时AT_MOST,且大小是父控件的可用大小。这和MATCH_PARENT时没有区别。因此在自定义View时,我们要处理View在WRAP_CONTENT时的这一问题。

  1. ViewGroup的measure过程
    ViewGroup比较简单,它的measure流程和View一样,作为其父控件的子View处理,不同的是,ViewGroup没有重写onMeasure方法,而是交给其子类去按需实现。
    以LinearLayout为例。LinearLayout会遍历子View,一次调用子View的measure方法,并纪录每个子View的测量值,最后再测量自己的大小。
获取View的宽高

因为Activity的生命周期和View的测量是异步的,所以并不能在Activity的生命周期函数中直接获取。通常可以通过以下几种方式获取:

  1. onWindowsFocusChanged
    这个回调函数在View初始化完成后调用,所以在这里获取宽高可以确保是View测量后的宽高。需要注意的是,该函数在Activity失去和获取焦点的时候都会触发。
public void onWindowsFocusChanged(boolean hasFocus){
     super.onWindowsFocusChanged(hasFocus);
     if (hasFocus) {
          int width = view.getMeasureWidth();
          int herght = view.getMeasureHeight();
     }
}
  1. view.post(runnable)
    此方法通过post将一个runnable投递到消息队列的尾部,因为在尾部,所以此runnable被Looper处理时,View已经测量完成了。
protected void omStart(){
    super.omStart();
    view.post(new Runnable(){
        @override
        public void run(){
            int width = view.getMeasureWidth();
            int herght = view.getMeasureHeight();
        }
    });
}
  1. ViewTreeObserverd的OnGlobalLayoutListener接口
    OnGlobalLayoutListener中的onGlobalLayout方法会在View树的状态发生变化时回调。注意,此方法回多次调用
protected void onStart(){
    super.onStart();
    ViewTreeOberver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override
         public void onGlobalLayout() {
         view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
         int width = view.getMeasureWidth();
         int herght = view.getMeasureHeight();
         }
    }
   )
}

4.view.measure(int widthMeasureSpec , int heightMeasureSpec)
手动触发测量

你可能感兴趣的:(View的Measure)