美文网首页我爱编程
View工作原理四:measure流程

View工作原理四:measure流程

作者: 水言 | 来源:发表于2018-07-26 09:45 被阅读47次

Window添加DecorView并绘制到手机屏幕上的流程:


在Activity中我们会通过XML布局文件的方式来配置UI,这个布局整体会作为子View添加到DecorView中。
XML中每个View必须要设置的两个属性是layout_width和layout_height,这两个属性代表着当前View的宽高。

它们可以设置的值:
1、固定的大小,比如60dp。
2、自适应,wrap_content。
3、父布局一样大,match_parent / fill_parent。
这两个属性的值最终会映射到屏幕上的具体像素,由于自适应尺寸机制的存在,需要在绘制前根据设置的layout_width和layout_height确定view在屏幕上占的大小。

measure流程就是用于测量View的宽高计算视图的大小。测量过程由ViewRootImp中对DecorView的测量开始,并不断向子View传递,依次测量所有的View,将测量结果保存在各自View的mMeasuredWidth和mMeasuredHeight中。

简单看看measure的整体测量流程

ViewRootImp#performTraversals:

private void performTraversals() {
...
  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
...
}
//
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
...
//mView就是DecorView
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
...
}

在ViewRootImp#performMeasure中调用了View#measure,measure(...)是final修饰的,子类无法重写,所以调用的就是View中的measure(...)。
View#measure:

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  //是否是是用了光学边界布局
      ...
  //根据标志位和MeasureSpec确定是否需要强制从新测量或需要测量
      ...
        if (forceLayout || needsLayout) {      
   //如果需要强制测绘或者没有缓存,执行onMeasure(),否者从缓存中取出数据
            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
//1*******************************************
                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;
            }
//保存数据,设置缓存
     ...
    }

DecorView继承Framelayout,重写了onMeasure(),所以//1**执行的就是DecorView#onMeasure。
DecorView#onMeasure:

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//针对mode == AT_MOST,从新计算widthMeasureSpec和heightMeasureSpec
    ...
//  获取mOutsets,当测绘模式mode != MeasureSpec.UNSPECIFIED时候,重新计算
        heightMeasureSpec和widthMeasureSpec。  
    ...
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//当!fixedWidth && widthMode == AT_MOST从新计算widthMeasureSpec ,measure字段设置为true
        ...
        if (measure) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
     }

整体流程就是判断是否需要更新heightMeasureSpec和widthMeasureSpec,需要时从新计算,然后调用其父布局FrameLayout的onMeasure(),Framelayout#onMeasure 具体在下面的ViewGroup的onMeasure中描述。

View的measure流程

上面已经说过View#measure,View#measure中会调用View#onMeasure。View的measure是被ViewGroup公用的,但是各种自定义的ViewGroup子类的onMeasure各自有实现。
View#onMeasure:

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

View#setMeasuredDimension中调用View#getDefaultSize;
View#getDefaultSize中调用了View#getSuggestedMinimumWidth()和View#getSuggestedMinimumHeight(),两者情况一致;

那么看看View#getSuggestedMinimumWidth():

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

如果没有背景,那么就是mMinWidth,对应android:mimWidth的值,如果设置了背景(mBackground是个Drawable),那么取mMinWidth和mBackground宽度的较大者。

View#getSuggestedMinimumWidth获取到值后传入View#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;
//这里可以得出结论:直接继承View的自定义控件,宽高设置为wrap_content时候效果和match_parent一致。
        case MeasureSpec.AT_MOST:   //对应的就是wrap_content
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

如果测量模式是MeasureSpec.UNSPECIFIED返回View#getSuggestedMinimumWidth获得的值,其他模式返回MeasureSpec中的值。

特别注意直接继承View的自定义控件,宽高设置为wrap_content时候效果和match_parent一致。

取到值后再看最外层的View#setMeasuredDimension:

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
//isLayoutModeOptical()中判断当前View是ViewGroup并且mLayoutMode == LAYOUT_MODE_OPTICAL_BOUNDS;
//LAYOUT_MODE_OPTICAL_BOUNDS这个属性,在布局的时候,View需要放在一个较大区域的布局内,以便留出来阴影之类位置

        boolean optical = isLayoutModeOptical(this);
//当前View和ViewParent 的isLayoutModeOptical不一致时候执行
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int opticalWidth  = insets.left + insets.right;
            int opticalHeight = insets.top  + insets.bottom;

            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
            measuredHeight += optical ? opticalHeight : -opticalHeight;
        }
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
    }

最后在View#setMeasuredDimension中调用View#setMeasuredDimensionRaw,将值保存

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
    }

ViewGroup的measure流程

对于ViewGroup而言,除了完成自己的measure过程,还会遍历所有子View的measure方法。
就ViewGroup而言,它是个抽象类,没有重写onMeasure方法,但是提供了一个ViewGroup#measureChildren:

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

protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();
       //父View的MeasureSpec,父View的pad,View自己的LayoutParams,计算出view的  MeasureSpec,,然后调用View#measure
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

View#measureChildren遍历每个状态不是GONE的View,执行ViewGroup#measureChild。
ViewGroup#measureChild会计算子View所需的MeasureSpec,然后调用View#measure。

ViewGroup没有定义onMeasure方法,但是其它子类,比如LinearLayout,RelativeLayout,FrameLayout针对自己的业务需求,测量细节会有所差异。
我们就来说说FrameLayout的onMeasure:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
//宽高有一个MeasureSpec的mode不是 MeasureSpec.EXACTLY
//就是说宽高属性有一个是不明确的
        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();
        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;
     //遍历找出所有子View宽高的所需要的最大值(宽高可能来自不同的View)
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
 1.具体看下面的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());
//如果FrameLayout自身的宽高不明确,并且子View属性有match_parent,保存起来,后面需要从新计算他们宽高
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

// 宽高加上pad,如果有前景色并且mInsidePadding=false,pad+前景色的pad,否者取两者的较大者,
2.具体看下面的FrameLayout#getPaddingLeftWithForeground
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // 取两者的较大者
3.具体看   FrameLayout# getSuggestedMinimumHeight
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

     //前景色图片的宽高和原先计算宽高的较大者
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

     //保存FrameLayout测量后所需要的大小
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));

//从新保存了FrameLayout大小,所以View属性是LayoutParams.MATCH_PARENT从新measure
//对于宽高中有一个是LayoutParams.MATCH_PARENT的View,重新计算MeasureSpec,
//然后调用child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

        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
4.看看getChildMeasureSpec
                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);
            }
        }
    }

简单描述过程就是在FrameLayout自身宽高不明确的时候,遍历找出子View 中最大的宽高,宽高可能来自不同的View,然后设置FrameLayout的宽高。确定了FrameLayout的大小后,接着如果属性有match_parent的View个数大于1,针对它们从新计算宽高。

1.ViewGroup#measureChildWithMargins

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

这个方法和上面说的 ViewGroup#measureChild很类似,就是在计算child的MeasureSpec加上了margin和widthUsed。
widthUsed和heightUsed的解释是父类或者父类中其他子类额外用掉的量。
ViewGroup#measureChildWithMargins最后会调用View#measure继续传递measure过程。

2.FrameLayout#getPaddingLeftWithForeground

  int getPaddingLeftWithForeground() {
        return isForegroundInsidePadding() ? Math.max(mPaddingLeft, mForegroundPaddingLeft) :
            mPaddingLeft + mForegroundPaddingLeft;
    }
    public boolean isForegroundInsidePadding() {
        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
    }

3.View#getSuggestedMinimumHeight

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

4.ViewGroup#getChildMeasureSpec

 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) {
        // 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.
                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.
                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
                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.
                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) {
                // 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;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }        

参考:《Android 开发艺术探索》

相关文章

网友评论

    本文标题:View工作原理四:measure流程

    本文链接:https://www.haomeiwen.com/subject/bcctmxtx.html