View Measure

252 阅读4分钟

前言

将一个view绘制在屏幕上我们需要知道这个view的大小,所以我们要先measure -》 然后根据规则放置view layout -》最后才是我们的draw 绘制出来。而这里measure是整个绘制流程的第一个,也是自定义View必须要了解的知识点。

MeasureSpec

定义

测量规格,封装了父容器对View的布局限制,内部提供了宽高的信息(SpecSize、SpecMode),SpecSize是指在某种SpecMode下的参考尺寸,其中SpecMode 有如下3种:

  • UNSPECIFIED 父控件不对你有任何限制,你想要多大就给你多大。这种情况一般用于系统内部(这个模式主要用于系统内部多次Measure情形,并不是真的说你想要多大最后真的有多大)
  • EXACTLY父控件已经知道你所需的精确大小,你的最终大小应该就这么大
  • AT_MOST你的大小不能大于父控件给你指定size的大小,具体多少有你来定

意义

通过将SpecMode 和 SpecSize 打包成一个int 值可以避免过多的对象分配内存,为了方便操作,其提供了打包和解包方法

	MeasureSpec.getMode() //解包方法
	MeasureSpec.getSize() //解包方法
  MeasureSpec.makeMeasureSpec() //打包方法

MeasureSpec

子View的MeasureSpec值是根据子View的布局参数(LayoutParams)和父容器的MeasureSpec值来计算得来的,具体计算逻辑封装在getChildMeasureSpec函数中。下面是ViewGroup 里面的获取子View MeasureSpec的方法:

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

    int resultSize = 0;
    int resultMode = 0;

    switch (specMode) {
    // 父控件的测量模式是EXACTLY模式, 也就是有精确的尺寸
    case MeasureSpec.EXACTLY:
        if (childDimension >= 0) {
        // 当child的布局参数有固定值, 比如 layout_height = “100dp”
        // 那么child的规格也就确定下来了 大小为 size = 100dp; mode = MeasureSpec.EXACTLY
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
          // Child 占满父控件,而父控件是EXACTLY 模式,所以模式和大小就确定了
            resultSize = size;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
          // child 大小自己控制,但是不能超过父大小,测量模式是AT_MOST
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // 父控件也不知道自己的大小,需要计算,但是大小不能超过size
    case MeasureSpec.AT_MOST:
        if (childDimension >= 0) {
            // child 指定尺寸
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child 想要跟父控件一样大,但是父控件也未知,所以child 大小未知 大小不能超过size
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
          // child 大小自己控制,但是不能超过父大小,测量模式是AT_MOST
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent asked to see how big we want to be
    case MeasureSpec.UNSPECIFIED:
        if (childDimension >= 0) {
            // 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
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        }
        break;
    }
    //noinspection ResourceType
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

View Measure 过程

measure

/**
* View.java 文件中的测量方法,这个
*/
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
    long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
    if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

    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;
    final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
            && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
    final boolean needsLayout = specChanged
            && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);

    if (forceLayout || needsLayout) {
        // first clears the measured dimension flag
        mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

        resolveRtlPropertiesIfNeeded();

        int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
        if (cacheIndex < 0 || sIgnoreMeasureCache) {
            // measure ourselves, this should set the measured dimension flag back
            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);
            // 更新flag3标志位,在layout的时候需要调用onMeasure。这样做的目的猜想-》“有时候我们的mesure方法会多次调用(尤其是在特殊的父控件 会多次进行子View的测量),这样避免我们多次执行onMeasure 方法 减少计算量,提高性能。直到你真正layout的时候发现你未调用onMeasure 才执行一次 ”
            mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        // flag not set, setMeasuredDimension() was not invoked, we raise
        // an exception to warn the developer
        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的标志位置为1,表示我已经测量计算过View大小了,layout需要跟着变化
        mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
    }
    
    mOldWidthMeasureSpec = widthMeasureSpec;
    mOldHeightMeasureSpec = heightMeasureSpec;

    mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
            (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
}

requestLayout

调用requestLayout之后我们Measure流程就会调用onMeasure方法

public void requestLayout() {
    if (mMeasureCache != null) mMeasureCache.clear();

    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
        // Only trigger request-during-layout logic if this is the view requesting it,
        // not the views in its parent hierarchy
        ViewRootImpl viewRoot = getViewRootImpl();
        if (viewRoot != null && viewRoot.isInLayout()) {
            if (!viewRoot.requestLayoutDuringLayout(this)) {
                return;
            }
        }
        mAttachInfo.mViewRequestingLayout = this;
    }

  //这里将我们Flag的forceLayout标志为设为1
    mPrivateFlags |= PFLAG_FORCE_LAYOUT;
    mPrivateFlags |= PFLAG_INVALIDATED;

    if (mParent != null && !mParent.isLayoutRequested()) {
        mParent.requestLayout();
    }
    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
        mAttachInfo.mViewRequestingLayout = null;
    }
}