016.View的测绘基础MeasureSpec

在学习onMeasure方法前,首先要掌握MeasureSpec这个类。MeasureSpec 主要是通过父容器的LayoutParams上的规则生成的,它影响到了测量的时候View的宽高。

1.阅读MeasureSpec源码

下面开始从源码开始阅读,源码上有一些注释,我就先自己翻译成中文:

/**
     *一个MesasureSpec代表着从父容器到子控件的布局需求。
     *每一个MesureSpec都代表着宽度和高度的需求
     * 一个MeasureSpec对象都由大小(size)和模式(mode)组成,模式包含了一下几种:
     * UNSPECIFIED
     * 父控件对子控件没有加任何的限制,子控件想要多大就给子控件多大。
     * EXACTLY
     * 子控件的大小就是父控件指定的大小。
     *
     * <dt>AT_MOST</dt>
     *父控件给了一个最大的大小,View的大小不能超出这个大小。
     *MeasureSpec 是通过int数值来实现的,这样避免了对象的分配。
      * 这个类提供了使用int来对大小(size) ,模式(mode),tuple(数组)进行封装和解析
     */
    public static class MeasureSpec {
        //代表后面30位放size
        private static final int MODE_SHIFT = 30;
        //0x3 也就是11 右移30位,成11000000000000000000000000000000 ,后面30位放size相关的内容
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        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;

        /**
         * 
         *
         * mode值必须为下面中的某一个
         * 
         *  ●  android.view.View.MeasureSpec#UNSPECIFIED 
         *  ●  android.view.View.MeasureSpec#EXACTLY 
         *  ● android.view.View.MeasureSpec#AT_MOST 
         * 
         * 记住: 在Android版本17以及以下的版本中, makeMeasureSpec这个方法的实现和参数的顺序无关
         * 并且还会造成值溢出影响到MeasurSpec的值,android.widget.RelativeLayout就受到了这个BUG的影响。
         *在API17开始,这个BUG就被修复了,并且加之以更严格的规则。
         *
         * @param size 指定的测量的大小
         * @param mode 指定的测量模式
         * @return 根据大小和模式返回测量规格
         */
        public static int makeMeasureSpec(int size, int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

        /**
         * 从指定的测量规格中获取到模式(非运算清除掉后30位的内容)
         */
        public static int getMode(int measureSpec) {
            return (measureSpec & MODE_MASK);
        }

        /**
         *从指定的测量规格中获取到大小(非运算清除掉前2位的内容保留后30位的内容)
 
         */
        public static int getSize(int measureSpec) {
            return (measureSpec & ~MODE_MASK);
        }
        /**根据阙值调整MeasureSpec的大小*/
        static int adjust(int measureSpec, int delta) {
            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
        }

        /**
         * Returns a String representation of the specified measure
         * specification.
         *
         * @param measureSpec the measure specification to convert to a String
         * @return a String with the following format: "MeasureSpec: MODE SIZE"
         */
        public static String toString(int measureSpec) {
            int mode = getMode(measureSpec);
            int size = getSize(measureSpec);

            StringBuilder sb = new StringBuilder("MeasureSpec: ");

            if (mode == UNSPECIFIED)
                sb.append("UNSPECIFIED ");
            else if (mode == EXACTLY)
                sb.append("EXACTLY ");
            else if (mode == AT_MOST)
                sb.append("AT_MOST ");
            else
                sb.append(mode).append(" ");

            sb.append(size);
            return sb.toString();
        }
    }

到这里,我们这边只有一个疑问,就是后面30位的内容是怎么放的,什么规则了,用法。关于MeasureSpec的用法,那和LayoutParams有比较大的关系。下面就开始介绍MeasureSpec和LayoutParams的关系.
我们对一个View进行布局,往往是这三个参数:match_parent 、wrap_content、 以及指定的大小。我们在前面说过ViewRootImpl参与到了DecorView的测量、绘制等过程,在ViewRootImpl的 measureHierarchy方法中可以看到MesureSpec生成的过程:

   childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
接着进入 getRootMeasureSpec 这个方法:

  private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

可以看到DecorView的MeasureSpec是和WindowSize以及自身的LayoutParams有关的。上面也让我们知道了match_parent 、wrap_content、 以及指定的大小和签名说的SpecMode的关系了。
那么,现在问题来了,MeasureSpec这个类,用在哪里。我们知道,decorView是FrameLayout 他本身也是ViewGroup的派生类,其他的容器,也都是继承与ViewGroup。之前我们知道,绘制流程是在ViewRoot开始传递的,我们现在看到ViewRootImpl的#performTraversals方法中,有调用performMeasure方法,performMeasure会调用View的measure->onMeasure方法,我们可以看到在LinearLayout的onMeasure方法中,
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == VERTICAL) {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        }
    }

LinearLayout中的measure过程比较复杂,还受到了父容器传入的MeasureSpec参数的影响,这点我们从onMeasure方法的声明就可以看到了,我们直接拉到最后一行,看
 if (matchWidth) {
            forceUniformWidth(count, heightMeasureSpec);
        }

 private void forceUniformWidth(int count, int heightMeasureSpec) {
        // Pretend that the linear layout has an exact size.
        int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(),
                MeasureSpec.EXACTLY);
        for (int i = 0; i< count; ++i) {
           final View child = getVirtualChildAt(i);
           if (child.getVisibility() != GONE) { 
               LinearLayout.LayoutParams lp = ((LinearLayout.LayoutParams)child.getLayoutParams());

               if (lp.width == LayoutParams.MATCH_PARENT) {
                   // Temporarily force children to reuse their old measured height
                   // FIXME: this may not be right for something like wrapping text?
                   int oldHeight = lp.height;
                   lp.height = child.getMeasuredHeight();

                   // Remeasue with new dimensions
                   measureChildWithMargins(child, uniformMeasureSpec, 0, heightMeasureSpec, 0);
                   lp.height = oldHeight;
               }
           }
        }
    }

这里面调用了 measureChildWithMargins 来测量子控件的大小,measureChildWithMargins是在ViewGroup方法中声明的,我们可以看到如下:


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

可以看到, getChildMeasureSpec方法中生成的childWidthMeasureSpec  会传递给child用于测量,而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 = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

 
从上面就可以看到child的MeasureSpec的创建流程,它不仅仅是受到了我们给的布局参数的影响(比如layout_width),还受到了父容器的MeasureSpec的影响。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值