组件的测量

1、简介

组件在显示到界面上要经过三个过程测量、布局、绘制。测量就是计算组件的大小,布局就是摆放组件的位置,而绘制就是把计算好的大小和位置绘制到画布上。下面就在说说组件测量的那些事。组件的onMeasure方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

2、组件测量的3种类型

widthMeasureSpec和heightMeasureSpec是什么呢?他是一个测量规则,一个32位int值,前两位表示测量的模式,低30位表示测量的大小。组件也提供对应的方法来获取他们的值。

final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);

通过size和mode也可以生成对应的测量规则

MeasureSpec.makeMeasureSpec(resultSize, resultMode);

测量模式有3种
EXACTLY
精确模式,当组件的长宽是具体值,如:

android:layout_width="200dp"

或是指定为match_parent(占据父view的大小),系统使用这个模式。

AT_MOST
最大值模式,当控件的长宽属性为warp_content时,组件的大小随自身的大小变化而变化,并且控件的尺寸不能超过父view允许最大尺寸。

UNSPECIFIED
不指定组件的大小,组件想多大就多大,通常在绘制自定义view时才会使用。

3、从源码来看组件测量过程

先来看View源码里的测量方法:

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

setMeasuredDimension方法接受测量后的长和宽,并赋值给组件,这样组件就有长宽。那如何计算长宽呢,看下面的代码:

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

getDefaultSize方法接收两个参数,一个是大小(系统传入的是组件的最小宽度或高度getSuggestedMinimumWidth()),一个是测量的规则。
通过测量规则获得测量的模式和指定的大小,
如果测量模式为MeasureSpec.UNSPECIFIED,则返回传入的大小为组件大小,及最小宽高;
如果测量模式为MeasureSpec.AT_MOST或MeasureSpec.EXACTLY,则返回父视图指定的大小。
再来看下ViewGroup中的测量实现,要实现ViewGroup的测量必须实现其子类的测量,但是ViewGroup中并没有重写onMeasure方法,需要具体实现类自己重写,但是他提供一些方法来便于我们测量子视图。

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();
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,            mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,            mPaddingTop + mPaddingBottom, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

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里会再调用onMeasure方法执行视图的测量。这里的关键实际上就是计算出子视图的测量规则measureSpec,及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);
}

这个方法接收3个参数
spec,父视图的测量规则,可以计算出父视图的测量模式和测量大小
padding,用于计算扣除padding后的视图大小
childDimension,视图布局中定义的宽高大小
通过不同的模式来计算出子视图的大小和模式从而转换为测量规则

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:
       ...
        break;
    case MeasureSpec.AT_MOST:
       ...
        break;
    case MeasureSpec.UNSPECIFIED:
        ...
       break;
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

父视图为精确模式
1、子视图有定义具体的大小,resultSize为定义的具体大小,模式为MeasureSpec.EXACTLY
2、子视图的childDimension为LayoutParams.MATCH_PARENT,resultSize为定义的具体大小,模式为MeasureSpec.EXACTLY
3、子视图的childDimension为LayoutParams.WRAP_CONTEN,resultSize为定义的具体大小,模式为MeasureSpec.AT_MOST
其他两种情况也是类似,源码中已经描述的很清楚了。最后调用MeasureSpec.makeMeasureSpec(resultSize, resultMode);方法就获得了子视图的测量规则。
再回顾前面说的View的测量,就能确定具体的View的测量大小。视图的整个测量过程就是这样,关键还是在要理解清楚MeasureSpec测量规则的使用。

4、测量在实际开发中的应用

 具有最大高度的滚动视图
 通过计算ScrollView子视图的高度,超过设置的最大高度,则设置Scrollview的高度为最大高度,如果没有超过,则按子视图的高度来显示scrollview。

具体的代码如下:

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int mMaxHeight = height > maxHeight ? maxHeight : height;
    View child = getChildAt(0);
    int child_height = child.getHeight();
    if (child_height == 0)
        child_height = mMaxHeight;
    else if (child_height > maxHeight)
        child_height = maxHeight;
    setMeasuredDimension(width, child_height);
}

5、注意事项

1、要区分getMeasuredHeight()与getHeight()的区别,getMeasuredHeight()是测量时的大小,组件有可能会测量多次,多次测量的大小有可能不一样,getHeight()是要绘制的大小
2、视图只有测量过后,getMeasuredHeight()方法才会有值,不然返回的是0

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

推荐阅读更多精彩内容