View的MeasureSpec理解。

1、理解MeasureSpec
MeasureSpec 很大程度上决定了一个View的尺寸规格。 之所以说是很大程度是因为这个过程还受父容器的影响, 因为父容器影响View的MeasureSpec的创建过程。在测量中系统会将View的Layoutparams根据父容器所施加的规则转化成对应的MeasureSpec。 然后在根据这个measureSpec来测量View的宽高。 这里不一定等于View的最终宽高。

public static class MeasureSpec {
 private static final int MODE_SHIFT = 30;
 private static final int MODE_MASK = 0x3 << MODE_SHIFT;

 /**
 * Measure specification mode: The parent has not imposed any constraint
 * on the child. It can be whatever size it wants.
 */
 public static final int UNSPECIFIED = 0 << MODE_SHIFT;

 /**
 * Measure specification mode: 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.
 */
 public static final int EXACTLY = 1 << MODE_SHIFT;

 /**
 * Measure specification mode: The child can be as large as it wants up
 * to the specified size.
 */
 public static final int AT_MOST = 2 << MODE_SHIFT;

 /**
 * Creates a measure specification based on the supplied size and mode.
 *
 * The mode must always be one of the following:
 * <ul>
 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
 * </ul>
 *
 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
 * implementation was such that the order of arguments did not matter
 * and overflow in either value could impact the resulting MeasureSpec.
 * {@link android.widget.RelativeLayout} was affected by this bug.
 * Apps targeting API levels greater than 17 will get the fixed, more strict
 * behavior.</p>
 *
 * @param size the size of the measure specification
 * @param mode the mode of the measure specification
 * @return the measure specification based on size and mode
 */
 public static int makeMeasureSpec(int size, int mode) {
 if (sUseBrokenMakeMeasureSpec) {
 return size + mode;
 } else {
 return (size & ~MODE_MASK) | (mode & MODE_MASK);
 }
 }

 /**
 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
 * will automatically get a size of 0. Older apps expect this.
 *
 * @hide internal use only for compatibility with system widgets and older apps
 */
 public static int makeSafeMeasureSpec(int size, int mode) {
 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
 return 0;
 }
 return makeMeasureSpec(size, mode);
 }

 /**
 * Extracts the mode from the supplied measure specification.
 *
 * @param measureSpec the measure specification to extract the mode from
 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
 * {@link android.view.View.MeasureSpec#AT_MOST} or
 * {@link android.view.View.MeasureSpec#EXACTLY}
 */
 public static int getMode(int measureSpec) {
 return (measureSpec & MODE_MASK);
 }

 /**
 * Extracts the size from the supplied measure specification.
 *
 * @param measureSpec the measure specification to extract the size from
 * @return the size in pixels defined in the supplied measure specification
 */
 public static int getSize(int measureSpec) {
 return (measureSpec & ~MODE_MASK);
 }
...
}

View的三种测量模式:
UNSPECIFIED:父容器不对View有任何限制,要多大给多大。
EXACTLY: 父容器已经检测出View所需要的精确大小,这个时候View的大小就是SpecSIze所指定的值。他对应于LayoutParams中的match_parent和具体的数值这两种模式。
AT_MOST:父容器指定了一个可用大小SpecSize。View的大小不能超过这个值,它对应于LayoutParams的wrap_content。(例如:父布局width或者height设置一个具体值,或者match_parent,子布局设置为wrap_content。此时子布局的最大width或者height就是父布局的width或者height)。使用这种测量模式的View,设置的一定是wrap_content。

2.MeasureSpec 和 LayoutParams的关系
系统内部是通过MeasureSpec来进行View的测量。 在View测量时,系统将LayoutParams在父容器的的约束下转换成对应的MeasureSpec,然后再根据这个MeasureSpec来确定View测量后的宽高。MeasureSpec不是唯一由LayoutParams决定的. LayoutParams需要和父容器一起才能决定View的MeasureSpec。从而进一步决定View的宽高。 对于普通View,MeasureSpec是由父容器的MeasureSpec和自身的Layoutparams来共同决定。 MeasureSpec一旦确定后,onMeasure中就可以确定View的测量宽高。普通的View的measure过程由ViewGroup传递而来。
以下下是ViewGroup的measureChildWidthMargins方法:

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

上述方法对子元素进行measure,在调用子元素的measure方法前先通过getChildMeasureSpec来得到子元素的MeasureSpec。 从代码来看。子元素的MeasureSpec的创建好父容器的MeasureSpec和自己本身的LayoutParams有关。此外还和View的margin和padding有关。
具体情况可以看下ViewGroup的getChildMeasuerSpec的方法。
来自博客:http://www.jianshu.com/p/e43a78deab86

    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:
            //如果child的布局参数有固定值,比如"layout_width" = "100dp"
            //那么显然child的测量规格也可以确定下来了,测量大小就是100dp,测量模式也是EXACTLY
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } 

            //如果child的布局参数是"match_parent",也就是想要占满父控件
            //而此时父控件是精确模式,也就是能确定自己的尺寸了,那child也能确定自己大小了
            else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            }
            //如果child的布局参数是"wrap_content",也就是想要根据自己的逻辑决定自己大小,
            //比如TextView根据设置的字符串大小来决定自己的大小
            //那就自己决定呗,不过你的大小肯定不能大于父控件的大小嘛
            //所以测量模式就是AT_MOST,测量大小就是父控件的size
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // 当父控件的测量模式 是 最大模式,也就是说父控件自己还不知道自己的尺寸,但是大小不能超过size
        case MeasureSpec.AT_MOST:
            //同样的,既然child能确定自己大小,尽管父控件自己还不知道自己大小,也优先满足孩子的需求
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } 
            //child想要和父控件一样大,但父控件自己也不确定自己大小,所以child也无法确定自己大小
            //但同样的,child的尺寸上限也是父控件的尺寸上限size
            else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            //child想要根据自己逻辑决定大小,那就自己决定呗
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                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);
    }

以上方法的理解:根据父容器的MeasureSpec同时结合View的本身LayoutParams来确定子元素的MeasureSpec。 参数中的padding是指父容器中已经占用的空间大小。因此元素可用的大小为父容器的尺寸减去padding。
将以上方法整理成表格:

1f7debd381be.png

注意, 当View采用固定宽高时, 不管富容器的MeasureSpec是什么, View的MeasureSpec都是EXACTLY,并且其大小遵循LayoutParams中的大小。 当View的宽高是match_parent时。如果父容器的模式是EXACTLY那么View也是EXACTLY, 其大小是父容器剩余空间。如果父容器是AT_MOST。那么View也是AT_MOST,并且最大值不会超过父容器的剩余空间。当View的宽高是wrap_content时。无论父容器是exactly还是at_most。View总是at_most

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容