Android-View-Measure测量过程分析

Android-View-measure测量过程分析

一、概述

我们知道android的View类的布局渲染包括三个部分,测量视图,布局视图,绘制视图

分别对应的measure、layout、draw

今天我们来分析下measure这个过程

二、问题

1、整体的流程是什么

2、过程分析和解读

3、MeasureSpec解读

4、例子分析

三、分析

1、整体的流程是什么

image

上面这个图很好的展示了View、ViewRootImpl、ViewGroup的调用过程

扫描二维码关注公众号,回复: 13395187 查看本文章

总结起来:measure的过程是不断的从根视图往子视图,不断测量的过程,直到最后一个子视图测量完成

2、过程分析和解读

上面我们了解了整个测量的调用过程了,那么我们现在来详细的看下这个过程

具体的View的绘制流程在我的另外一边文章有写(Android-View的绘制流程分析 https://editor.csdn.net/md/?articleId=121084883)

我们就从ViewRootImpl的performMeasure开始说起(performMeasure是在performTraversals中调用的)

1、ViewRootImpl#performMeasure

2013                      int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
2014                      int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
2015  
2016                      if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
2017                              + mWidth + " measuredWidth=" + host.getMeasuredWidth()
2018                              + " mHeight=" + mHeight
2019                              + " measuredHeight=" + host.getMeasuredHeight()
2020                              + " coveredInsetsChanged=" + contentInsetsChanged);
2021  
2022                       // Ask host how big it wants to be
2023                      performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

上面这个方法是ViewRootImpl中的performMeasure里的,计算了屏幕的高宽,加上sizemode,传入到performMeasure中

2、ViewRootImpl#performMeasure
 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
    
    
2273          Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2274          try {
    
    
2275              mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2276          } finally {
    
    
2277              Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2278          }
2279      }

这个方法很短,就是调用了mView的measure,这个mView是DectorView,继承自Framelayout,DectorView是顶层视图

这个measure是View中的方法,我们来继续看下

3、View#measure()
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    
    
    boolean optical = isLayoutModeOptical(this);
    if (optical != isLayoutModeOptical(mParent)) {
    
    
        Insets insets = getOpticalInsets();
        int oWidth  = insets.left + insets.right;
        int oHeight = insets.top  + insets.bottom;
        widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
        heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
    }

    // Suppress sign extension for the low bytes
    /*
    计算得到一个measure缓存的key
    这个key从代码可以看出,是一个long类型,高32位是宽度width,低32位是高度组成的
    */
    long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
    if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
	//如果强制布局了,这里这个强制布局是指的是用户调用了requestLayout这个,
    //requestLayout调用后mPrivateFlags |= PFLAG_FORCE_LAYOUT 添加了这个标志
    final boolean forceLayout = (mPrivateFlags |=  & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;

    // Optimize layout by avoiding an extra EXACTLY pass when the view is
    // already measured as the correct size. In API 23 and below, this
    // extra pass is required to make LinearLayout re-distribute weight.
    //如果测量前后尺寸改变
    final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
            || heightMeasureSpec != mOldHeightMeasureSpec;
    //如果宽和高都是精确值
    final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
            && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
    //如果现在View里的高宽和当前父视图传入的宽高一样
    final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
            && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
    //如果下面的条件 就需要布局
    final boolean needsLayout = specChanged
            && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
	//如果调用了requestLayout 或则 满足needsLayout 就测量
    if (forceLayout || needsLayout ) {
    
    
        // first clears the measured dimension flag
        //删除开始测量的标记
        mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
		//设置rtl,这个是从右边往左边读的配置
        resolveRtlPropertiesIfNeeded();
		//从缓存中提取缓存index。然后根据这个判断是否有缓存
        int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
        if (cacheIndex < 0 || sIgnoreMeasureCache) {
    
    
            // measure ourselves, this should set the measured dimension flag back
            //如果没有缓存就直接走onMeasure
            onMeasure(widthMeasureSpec, heightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        } else {
    
    
            //如果有缓存就走缓存设置
            long value = mMeasureCache.valueAt(cacheIndex);
            // Casting a long to int drops the high 32 bits, no mask needed
            setMeasuredDimensionRaw((int) (value >> 32), (int) value);
            mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        // flag not set, setMeasuredDimension() was not invoked, we raise
        // an exception to warn the developer
        //不管上面走不走缓存都必须设置测量的结果,就是必须调用setMeasuredDimension
        //setMeasuredDimension调用后PFLAG_MEASURED_DIMENSION_SET标志会被添加
        //不然抛异常
        if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
    
    
            throw new IllegalStateException("View with id " + getId() + ": "
                    + getClass().getName() + "#onMeasure() did not set the"
                    + " measured dimension by calling"
                    + " setMeasuredDimension()");
        }
		//测量完成,开始添加布局layout的request的标志位PFLAG_LAYOUT_REQUIRED,准备layout操作
        mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
    }
	//设置自己的宽度和高度
    mOldWidthMeasureSpec = widthMeasureSpec;
    mOldHeightMeasureSpec = heightMeasureSpec;
	//添加缓存
    mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
            (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
}

上面的代码我做了很充分的注释

总的来说这个方法主要干了1件事情,调用自己的onMeasure,这个onMeasure是子类需要重写的方法,这个设计就增强了View的扩展性

4、View#onMeasure()或者ViewGroup子类#onMeasure()

这里View不是ViewGroup,比如是TextView,就直接走onMeasure,这里就结束了,

如果是ViewGroup,因为ViewGroup没有对onMeasure重写,所以我要看下子类是如何做的

这里我就用Framelayout为例子看下,这里只简单说下,后面在例子中会详细说下这个方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
    
    int count = getChildCount();

    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循环主要是遍历子类视图,然后分辨对子视图测量
    //测量子视图后,又回到前面的那个循环了
    for (int i = 0; i < count; i++) {
    
    
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
    
    
            //调用ViewGroup的measureChildWithMargins方法
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            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());
            if (measureMatchParentChildren) {
    
    
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
    
    
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

    // Account for padding too
    maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
    maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

    // Check against our minimum height and width
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

    // Check against our foreground's minimum height and width
    final Drawable drawable = getForeground();
    if (drawable != null) {
    
    
        maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
        maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
    }

    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));

    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();

            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);
            }

            final int childHeightMeasureSpec;
            if (lp.height == LayoutParams.MATCH_PARENT) {
    
    
                final int height = Math.max(0, getMeasuredHeight()
                        - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                        - lp.topMargin - lp.bottomMargin);
                childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                        height, MeasureSpec.EXACTLY);
            } else {
    
    
                childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                        lp.topMargin + lp.bottomMargin,
                        lp.height);
            }

            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}
5、ViewGroup#measureChildWithMargins
protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    
    
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
	//这个方法会根据 传入的参数计算出合适的测量值,这些都和xml布局中的match,warp,或者准确数值有关
    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);
	//核心代码,这里就调用了子视图的measure方法,循环回去了
    //下面这个child 有可能是View也有可能是ViewGroup 
    //如果是View的画 就会调用自身的onMeasure 过程就结束了
    //如果是ViewGroup,那么就回到了之前ViewRootImpl的measure的那个点那里
    //向下循环开始...
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

到此整个的过程分析完了

3、MeasureSpec解读

上面的分析中重复的出现了MeasureSpec类,我们来看下这个类什么样的

这个类是View的内部静态类

public static class MeasureSpec {
    
    
    private static final int MODE_SHIFT = 30;
    private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

    /** @hide */
    @IntDef({
    
    UNSPECIFIED, EXACTLY, AT_MOST})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MeasureSpecMode {
    
    }


    public static final int UNSPECIFIED = 0 << MODE_SHIFT;

    public static final int EXACTLY     = 1 << MODE_SHIFT;

    public static final int AT_MOST     = 2 << MODE_SHIFT;

    public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                      @MeasureSpecMode int mode) {
    
    
        if (sUseBrokenMakeMeasureSpec) {
    
    
            return size + mode;
        } else {
    
    
            return (size & ~MODE_MASK) | (mode & MODE_MASK);
        }
    }

    @UnsupportedAppUsage
    public static int makeSafeMeasureSpec(int size, int mode) {
    
    
        if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
    
    
            return 0;
        }
        return makeMeasureSpec(size, mode);
    }

    @MeasureSpecMode
    public static int getMode(int measureSpec) {
    
    
        //noinspection ResourceType
        return (measureSpec & MODE_MASK);
    }

  
    public static int getSize(int measureSpec) {
    
    
        return (measureSpec & ~MODE_MASK);
    }

    static int adjust(int measureSpec, int delta) {
    
    
        final int mode = getMode(measureSpec);
        int size = getSize(measureSpec);
        if (mode == UNSPECIFIED) {
    
    
            // No need to adjust size for UNSPECIFIED mode.
            return makeMeasureSpec(size, UNSPECIFIED);
        }
        size += delta;
        if (size < 0) {
    
    
            Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
                    ") spec: " + toString(measureSpec) + " delta: " + delta);
            size = 0;
        }
        return makeMeasureSpec(size, mode);
    }

MeasureSpec的精妙之处在于只通过一个int类型就可以标识尺寸的模式还有尺寸的数值,内存开销少,参数传递简洁

MeasureSpec的宽度和高度都是int类型,int类型是4个字节,32位,高2位是mode,低30位是数值

举个例子

00000000 00000000 00000001 00101100 高2位是00,代表 UNSPECIFIED 低30位是数值300

01000000 00000000 00000001 00101111 高2位是01,代表 EXACTLY低30位是数值303

10000000 00000000 00000001 00102100 高2位是10,代表 AT_MOST低30位是数值284

如果我们要提取这个int数字中的mode怎么办呢?

以00000000 00000000 00000001 00101100位例子,我们只需要11000000 00000000 00000000 00000000

做按位与&操作就可以得到mode值了

实际MeasureSpec也是这么做的,MODE_MASK=3<<30 其实就是上面那个11000000 00000000 00000000 00000000

@MeasureSpecMode
    public static int getMode(int measureSpec) {
    
    
        //noinspection ResourceType
        return (measureSpec & MODE_MASK);
    }

提取size呢?和上面提取mode同理操作就可以了

public static int getSize(int measureSpec) {
    
    
    //这里这个~MODE_MASK=00111111  11111111  11111111 11111111
    //按位& 就可以获得后面的size
        return (measureSpec & ~MODE_MASK);
    }

如果把mode和size合并位一个int呢?

//参数通过注解 设置了取值范围,这里这个size 不是完全的int的范围,因为高2位被占用了  
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                      @MeasureSpecMode int mode) {
    
    
      //sUseBrokenMakeMeasureSpec 这个不用管,是一个新老版本的代码问题,sdk》17后 就用下面的方式了
        if (sUseBrokenMakeMeasureSpec ) {
    
    
            return size + mode;
        } else {
    
    
            //经过上面的讲解,相信下面的写法,你也可以理解了
            return (size & ~MODE_MASK) | (mode & MODE_MASK);
        }
    }


我们再来说下这个mode

  • 当 specmode 为 UNSPECIFIED 时,意思是视图没有规定,子视图使用自身期望的大小;
  • 当 specmode 为 EXACTLY 时,使用指定视图使用了的确定的值(通常为layoutparams中确定的值);
  • 当 specmode 为 AT_MOST 时,判断自身期望是否超过父 view 的限制,若未超过,则使用自身期望的值,若超过,则使用父view限制的最大值。

4、例子

这里我们就用Framelayout的onMeasure来讲解,看看是如何实现的

这个方法的目的就是计算自身的尺寸还有计算子视图的尺寸

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
    
    int count = getChildCount();
	//这个的作用是标记当前这个Framelayout的长款尺寸是否是精确的的
    //如果是的话就不需要对里面的子视图进行第二次测量了
    //如果不是比如,含有at_most,就需要对自身精确测量后,再次测量子视图中含有MATCH_PARENT的子视图
    //整个过程大家可以体会,是不是这个逻辑
    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);
        //测量那些Visiable或者InVisiable的View,这里记住InVisiable的View也要测量,我们直到InVisiable也是要占用空间的
        //mMeasureAllChildren 如果设置了强制测量全部View的标志,就需要全部测量
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
    
    
            //测量子视图的大小,测量的时候需要计算Framelayout的pading还有Child的margin
            //计算完之后child就有了宽高,这个方法会触发子视图的measure树,测量下面的所有View
            //这里里面有个ViewGroup中很重要的方法:getChildMeasureSpec(int spec, int padding, int childDimension)
            //继承子ViewGroup的子类一般都直接调用measureChildWithMargins就可以了,这个规则是android系统的统一设置,用户一般不要自行改变
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            //获取最大值
            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());
            if (measureMatchParentChildren) {
    
    
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
    
    
                    //子视图的宽高中只要有一个等于MATCH_PARENT 就需要添加进去 后面重新测量
                    //因为之前不知道Framelayout的尺寸,测量不准确
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

    // Account for padding too
    //根据自身的padding 这个是前景图的的
    maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
    maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

    // Check against our minimum height and width
    //根据自身设置的最大值 最小值 计算尺寸
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

    // Check against our foreground's minimum height and width
    //如果设置了前景图,需要考虑前景图的尺寸的大小,也要算进去
    final Drawable drawable = getForeground();
    if (drawable != null) {
    
    
        maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
        maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
    }
	/*
	resolveSizeAndState:
	public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
		上面那个size是自己希望要的尺寸
        final int specMode = MeasureSpec.getMode(measureSpec);
        //specSize 是父视图结合自身的设置 给的尺寸
        final int specSize = MeasureSpec.getSize(measureSpec);
        final int result;
        switch (specMode) {
        //这个是尽可能的大,
            case MeasureSpec.AT_MOST:
            	//下面这个是取值最小那个
                if (specSize < size) {
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
                //尺寸确定了,那么就按照上面传下来的设置
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
                //如果没有任何要求,就设置子视图 小计算出来 想要的尺寸
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
    }
    这个方法就是根据mode来计算合适的尺寸,这个大家可以体会
	*/
    //这个方法就是设置Framelayout 自身的尺寸
    setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
            resolveSizeAndState(maxHeight, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));

    //下面这个就是要重新测量的View集合了,原因最上面已经说了
    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();

            final int childWidthMeasureSpec;
            if (lp.width == LayoutParams.MATCH_PARENT) {
    
    
                //getMeasuredWidth 这个值 之前已经测量完成了,跟之前的不一样,所以需要重新测量、
                //当子视图的宽度是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);
            }

            final int childHeightMeasureSpec;
            if (lp.height == LayoutParams.MATCH_PARENT) {
    
    
                final int height = Math.max(0, getMeasuredHeight()
                        - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                        - lp.topMargin - lp.bottomMargin);
                childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                        height, MeasureSpec.EXACTLY);
            } else {
    
    
                childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                        lp.topMargin + lp.bottomMargin,
                        lp.height);
            }
			//重新测量
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}

上面我们调用了measureChildWithMargins方法,经过跟踪,最终会调用到ViewGroup的getChildMeasureSpec

方法,这个是方法是ViewGroup的子类通用的测量规则,这个方法主要是通过父视图的建议尺寸和自己的设置情况计算出合理的,适合自己的尺寸

我们来看下

//childDimension 这个参数是child自己本身的设置尺寸,是自己希望的尺寸
//childDimension 这个尺寸包括具体的尺寸,也包括MATCH_PARENT,WRAP_CONTENT
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    
    
    //从spec中获取mode,这个mode之前说过,应该有三种类型,0,1,2
    int specMode = MeasureSpec.getMode(spec);
    //从spec中获取size,这个size是真正的数值
    int specSize = MeasureSpec.getSize(spec);
	//这个size 是刨去了padding 之后留给childview剩余的空间了,这个padding包括父视图的padding和自己
    //的margin,这个值是子视图尽可能最大的时候,能取到的最大值了
    int size = Math.max(0, specSize - padding);

    int resultSize = 0;
    int resultMode = 0;
	//这个方法主要就是对
    switch (specMode) {
    
    
    // Parent has imposed an exact size on us
    //这个的意思是父视图的尺寸是确定的,是一个准确的值
    case MeasureSpec.EXACTLY:
            
        if (childDimension >= 0) {
    
    
            //如果父视图尺寸确定,那么子视图如果设置了自己想要的确定尺寸,就给他那么大,超出也没问题
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
            
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
    
    
            // Child wants to be our size. So be it.
            //如果父视图尺寸确定,那么子视图设置了MATCH_PARENT,意思是尽可能最大,但是不超过父视图
            //所以这个size只能是父视图的size-padding
            //mode应该设置EXACTLY
            resultSize = size;
            resultMode = MeasureSpec.EXACTLY;
            
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
    
    
            // Child wants to determine its own size. It can't be
            // bigger than us.
            //如果父视图尺寸确定,那么子视图设置了WRAP_CONTENT,WRAP_CONTENT是自适应尺寸,那么子视图最大不能超过父视图给的空间,根据自己情况设置尺寸
            //那么这个mode=AT_MOST,
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent has imposed a maximum size on us
    case MeasureSpec.AT_MOST:
        if (childDimension >= 0) {
    
    
            // Child wants a specific size... so be it
            //子视图设置了精确的值,就应该设置他自己的值,模式也是EXACTLY
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
    
    
            // Child wants to be our size, but our size is not fixed.
            // Constrain child to not be bigger than us.
            //由于这个子视图 的父视图 或在在往上,肯定有个父视图设置了WRAP_CONTENT,所以自己也要设置为
            //AT_MOST
            //大小是父视图规定的最大范围
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
    
    
            // Child wants to determine its own size. It can't be
            // bigger than us.
            //
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent asked to see how big we want to be
    case MeasureSpec.UNSPECIFIED:
        if (childDimension >= 0) {
    
    
            //子视图设置了精确的值,就应该设置他自己的值,模式也是EXACTLY
            // Child wants a specific size... let him have it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
    
    
            // Child wants to be our size... find out how big it should
            // be
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
    
    
            // Child wants to determine its own size.... find out how
            // big it should be
            //这里有个sUseZeroUnspecifiedMeasureSpec,只是UNSPECIFIED 模式下返回0
            //这个是在sdk<23是这样的,大于23了就返回size了
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        }
        break;
    }
    //noinspection ResourceType
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

总结getChildMeasureSpec 规律:

1、子视图自身设置了明确的数值尺寸,那么子视图的数值结果就是这个值,模式是EXACTLY

2、如果父视图是AT_MOST ,除去1情况,那么子视图数值是父视图给的最大值,mode是AT_MOST

所以AT_MOST 这个模式,会一直往子视图下传递,直到遇到设置了精确数值的View

3、如果父视图UNSPECIFIED不确定的,除去1情况,那么子视图数值是父视图给的最大值,mode是UNSPECIFIED,所以UNSPECIFIED 这个模式,会一直往子视图下传递,直到遇到设置了精确数值的View

4、除了精确设置自己的尺寸外,数值上来将都是取父视图的留给子视图的最大值

四、总结

1、View中的measure过程就是从根视图触发,然后不断层层遍历子视图测量的过程,大家要深入理解这个过程

2、子视图在计算自己的尺寸时,要考虑父视图给的控件还有模式,还要考虑自己设置的数值,ViewGroup#getChildMeasureSpec这里实现了

3、MeasureSpec设计采用了一个int来标识mode和size,其中采用了位操作来实现,还是很精妙

到此View的测量分析就到此结束

猜你喜欢

转载自blog.csdn.net/fagawee/article/details/121136249