View的工作原理之Measure过程源码学习(四)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lin962792501/article/details/84881485

       上一篇文章,学习了ViewGroup和View的measure流程。文章最后讲到,本文将会学习ViewGroup和普通View的onMeasure方法的工作。

       因为ViewGroup是抽象类,它并没有实现onMeasure方法,而是选择让它的子类实现。之前学习DecorView的measure过程时,说到DecorView的父类继承自FrameLayout,FrameLayout又继承自ViewGroup,并且重写了onMeasure方法。那我们就来看一下FrameLayout的onMeasure方法。

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

      //...

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

      //...

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

         从代码可以看到,child.measure方法的调用参数childWidthMeasureSpec和childHeightMeasureSpec的生成,是与父容器的MeasureSpec值和child的LayoutParams有关的。很明显子元素的测量值,是去除了子元素本身的margin和padding值的。查看LinearLayoutRelativeLayout的源码,可以发现它们的onMeasure方法中,调用child.measure方法的调用参数也是去除了子元素本身的margin和padding值的。由此,我们可以知道,在自定义ViewGroup的时候,我们需要在重写的onMeasure方法中处理子元素的margin和padding值。注意到上述代码中子元素的childWidthMeasureSpec值可以是调用了getChildMeasureSpec获得的(childHeightMeasureSpec同理)。下面我们看一下它的源码:

 //VIewGroup.java 6602行
  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;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
  }

        从上面的getChildMeasureSpec方法源码(这里我们依然不分析UNSPECIFIED模式),结合上面FrameLayout(或者LinearLayout/RelativeLayout)的onMeasure方法,可以知道,getChildMeasureSpec方法的三个参数是:父容器的测量规格值、子元素的LayoutParams中的margin和子元素的padding值的和、子元素的LayoutParams中的width(或者LayoutParams中的height)。

        从源码可以总结出子元素MeasureSpec创建的规律,如下表。表格中,第一行表示父容器的测量模式,第一列表示子元素在父容器的约束下,子元素LayoutParams的值:

x:parentSpecMode

y:childLayoutParams

EXACTLY

AT_MOST

UNSPECIFIED

dp/px

EXACTLY

childSize

EXACTLY

childSize

EXACTLY

childSize

MATCH_PARENT

EXACTLY

parentSize

AT_MOST

parentSize

UNSPECIFIED

0

WRAP_CONTENT

AT_MOST

parentSize

AT_MOST

parentSize

UNSPECIFIED

0

        其中:parentSize是值父容器的测量值的大小减去子元素margin和padding占用的值。childSize就是子元素的LayoutParams中的width或者LayoutParams中的height的值。

下面我们看一下,ViewGroup给我们提供的一些关于Measure过程的方法。

//ViewGroup.java  6522行
 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);
          }
     }
 }

 //ViewGroup.java  6542行 
  protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
      final LayoutParams lp = child.getLayoutParams();

      final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
      final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

      child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  }

        ViewGroup能够拥有子元素,所以它的measure过程除了测量自己的大小以外,还需要遍历去调用所有子元素的measure方法。遍历子元素经行测量这个过程可以通过调用measureChildren方法实现,也可以自己在自定义的ViewGroup的onMeasure方法中实现。 

        measureChildren方法很简单,就是遍历ViewGroup的子元素,再根据子元素的可见状态调用measureChild方法。在measureChild方法中创建子元素的MeasureSpec,然后调用子元素的measure方法,如果子元素是ViewGroup那么重复这个过程。如果子元素是View,那就回到了View的measure过程了。

 //VIewGroup.java  6568行
  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的时候,可以自己实现对子元素的margin和padding的处理,也可以调用在这个方法。

       普通View的onMeasure方法相对ViewGroup简单些,根据父容器剩余空间,处理普通View的margin和padding,如果有额外的需求,加上这些需求的处理计算出普通View的宽高,调用setMeasuredDimension设置普通View全局宽高值即可。

猜你喜欢

转载自blog.csdn.net/lin962792501/article/details/84881485