View 绘制体系知识梳理(3) 绘制流程之 Measure 详解

1、测量过程的信使 - MeasureSpec

由于测量是一个从上到下的过程,而在这个过程中,父容器有必要告诉子View它的一些绘制要求,那么这时候就须要依赖一个信使,来传递这个要求,它就是MeasureSpec. MeasureSpec是一个32位的int类型,咱们把它分为高2位和低30位。 其中高2位表示mode,它的取值为:bash

  • UNSPECIFIED(0) : The parent has not imposed any constraint on the child. It can be whatever size it wants.
  • EXACTLY(1) : The parent has determined an exact size for the child. The child is going to be given those bounds regardless of how big it wants to be.
  • AT_MOST(2) : The child can be as large as it wants up to the specified size.

30位表示具体的sizeless

MeasureSpec是父容器传递给View的宽高要求,并非说它传递的size是多大,子View最终就是多大,它是根据**父容器的MeasureSpec和子ViewLayoutParams**共同计算出来的。ide

为了更好的理解上面这段话,咱们须要借助ViewGroup中的两个函数:函数

  • measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
  • getChildMeasureSpec(int spec, int padding, int childDimension)
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);
    }

    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) {
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }
复制代码

能够看到,在调用getChildMeasureSpec以前,须要考虑parentchild之间的间距,这包括parentpaddingchildmargin,所以,参与传递给childMeasureSpec的参数要考虑这么几方面:布局

  • 父容器的measureSpecpadding
  • Viewheightwidht以及margin

下面咱们来分析getChildMeasureSpec的具体流程,它对宽高的处理逻辑都是相同的,根据父容器measureSpecmode,分红如下几种状况:ui

1.1 父容器的modeEXACTLY

这种状况下说明父容器的大小已经肯定了,就是固定的值。this

  • View指定了大小 那么子Viewmode就是EXACTLYsize就是布局里面的值,这里就有疑问了,View所指定的宽高大于父容器的宽高怎么办呢?,咱们先留着这个疑问。
  • ViewMATCH_PARENTView但愿和父容器同样大,由于父容器的大小是肯定的,因此子View的大小也是肯定的,size就是父容器measureSpecsize - 父容器的padding - 子View``margin
  • ViewWRAP_CONTENT 子容器只要求可以包裹本身的内容,可是这时候它又不知道它所包裹的内容究竟是多大,那么这时候它就指定本身的大小就不能超过父容器的大小,因此modeAT_MOSTsize和上面相似。

1.2 父容器的modeAT_MOST

在这种状况下,父容器说明了本身最多不能超过多大,数值在measureSpecsize当中:spa

  • View指定大小 同上分析。
  • ViewMATCH_PARENTView但愿和父容器同样大,而此时父容器只知道本身不能超过多大,所以子View也就只能知道本身不能超过多大,因此它的modeAT_MOSTsize就是父容器measureSpecsize - 父容器的padding - 子View``margin
  • ViewWRAP_CONTENT 子容器只要求可以包裹本身的内容,可是这时候它又不知道它所包裹的内容究竟是多大,这时候虽然父容器没有指定大小,可是它指定了最多不能超过多少,这时候子View也不能超过这个值,因此modeAT_MOSTsize的计算和上面相似。

1.3 父容器的modeUNSPECIFIED

  • View指定大小 同上分析。
  • ViewMATCH_PARENTView但愿和父容器同样大,可是这时候父容器并无约束,因此子View也是没有约束的,因此它的mode也为UNSPECIFIEDsize的计算和以前一致。
  • ViewWRAP_CONTENTView不知道它包裹的内容多大,而且父容器是没有约束的,那么也只能为UNSPECIFIED了,size的计算和以前一致。

2、测量过程的起点 - performTraversals()

介绍完了基础的知识,咱们来从起点来整个看一下从View树的根节点到叶节点的整个测量的过程。 咱们先直接说明结论,整个测量的起点是在ViewRootImplperformTraversals()当中code

private void performTraversals() {
        ......
        int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
        int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
        //...
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
复制代码

上面的mView是经过setView(View view, WindowManager.LayoutParams attrs, View panelParentView)传进来的,那么这个view是何时传递进来的呢? 如今回忆一下,在ActivityThreadhandleResumeActivity中,咱们调用了ViewManager.add(mDecorView, xxx),而这个方法最终会调用到WindowManagerGlobal的下面这个方法:orm

public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) {
            root = new ViewRootImpl(view.getContext(), display);
        }
        //....
        root.setView(view, wparams, panelParentView);
    }
复制代码

也就是说,上面的**mView也就是咱们在setContentView当中渲染出来的mDecorView**,也就是说它是整个View树的根节点,由于mDecorView是一个FrameLayout,因此它调用的是FrameLayoutmeasure方法。 那么这整个从根节点遍历完整个View树的过程是怎么实现的呢? 它其实就是依赖于measureonMeasure

  • 对于Viewmeasure是在它里面定义的,并且它是一个final方法,所以它的全部子类都没有办法重写该方法,在该方法当中,会调用onMeasure来设置最终测量的结果,对于View来讲,它只是简单的取出父容器传进来的要求来设置,并无复杂的逻辑。
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);

        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -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);
                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()");
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
    }
复制代码
  • 对于ViewGroup,因为它是View的子类,所以它不可能重写measure方法,而且它也没有重写onMeasure方法。
  • 对于继承于View的控件,例如TextView,它会重写onMeasure,与View#onMeasure不一样的是,它会考虑更多的状况来决定最终的测量结果。
  • 对于继承于ViewGroup的控件,例如FrameLayout,它一样会重写onMeasure方法,与继承于View的控件不一样的是,因为ViewGroup可能会有子View,所以它在设置本身最终的测量结果以前,还有一个重要的任务:调用子Viewmeasure方法,来对子View进行测量,并根据子View的结果来决定本身的大小

所以,整个从上到下的测量,其实就是一个View树节点的遍历过程,每一个节点的onMeasure返回时,就标志它的测量结束了,而这整个的过程是以Viewmeasure方法为纽带的:

  • 整个过程的起点是mDecorView这个根节点的measure方法,也就是performTraversals中的那句话。
  • 若是节点有子节点,也就是说它是继承于ViewGroup的控件,那么在它的onMeasure方法中,它并不会直接调用子节点的onMeasure方法,而是经过调用子节点measure方法,因为子节点不可能重写View#measure方法,所以它最终是经过View#measure来调用子节点重写的onMeasure来进行测量,子节点再在其中进行响应的逻辑处理。
  • 若是节点没有子节点,那么当它的onMeausre方法被调用时,它须要设置好本身的测量结果就好了。

对于measureonMeasure的区别,咱们能够用一句简单的话来总结一下:measure负责进行测量的传递,onMeasure负责测量的具体实现

3、测量过程的终点 - onMeasure当中的setMeasuredDimension

上面咱们讲到设置的测量结果,其实测量过程的最终目的是:经过调用setMeasuredDimension方法来给mMeasureHeightmMeasureWidth赋值。 只要上面这个过程完成了,那么该ViewGroup/View/及其实现类的测量也就结束了,而**setMeasuredDimension必须在onMeasure当中调用,不然会抛出异常**,因此咱们观察全部继承于ViewGroup/View的控件,都会发现它们最后都是调用上面说的那个方法。 前面咱们已经分析过,measure只是传递的纽带,所以它的逻辑是固定的,咱们直接看各个类的onMeasure方法就好。

3.1 ViewonMeasure

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

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

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

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

这里,咱们会根据前面所说的,父容器传递进来measureSpec中的mode来给这两个变量赋值:

  • 若是modeUNSPECIFIED,那么说明父容器并不期望多个,所以子View根据本身的背景或者minHeight/minWidth属性来给本身赋值。
  • 若是是AT_MOST或者EXACTLY,那么就把它设置为父容器指定的size

3.2 ViewGrouponMeasure

因为ViewGroup的目的是为了容纳各子View,可是它并不肯定子View应当如何排列,也就不知道该如何测量本身,所以它的onMeasure是没有任何意义的,因此并无重写,而是应当由继承于它的控件来重写该方法。

3.3 继承于ViewGroup控件的onMeasure

为了方面,咱们以DecorView为例,通过前面的分析,咱们知道当咱们在performTraversals中调用它的measure方法时,最终会回调到它对应的控件类型,也就是FrameLayoutonMeasure方法:

@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 (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                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); } } } 复制代码

咱们能够看到,整个的onMeasure其实分为三步:

  • 遍历全部子View,调用measureChildWithMargins进行第一次子View的测量,在第一节中,咱们也分析了这个方法,它最终也是调用子Viewmeasure方法。
  • 根据第一步的结果,调用setMeasuredDimension来设置本身的测量结果。
  • 遍历全部子View,根据第二步的结果,调用child.measure进行第二次的测量。

这也验证了第二节中的结论:父容器和子View的关联是经过measure进行关联的。 同时咱们也能够有一个新的结论,对于View树的某个节点,它的测量结果有可能并非一次决定的,这是因为父容器可能须要依赖于子View的测量结果,而父容器的结果又可能会影响子View,可是,咱们须要保证这个过程不是无限调用的。

相关文章
相关标签/搜索