wrap_content/match_parent为何可以灵活控制视图的宽高

视图的宽高可以灵活变化

android对于的视图布局的定义提供了一种很灵活的实现,就是当给视图的宽高属性设置wrap_content/match_parent,视图可以根据所处布局的情况动态的改变宽高。

wrap_content:根据自视图的内容决定视图大小
match_parent:占满父视图空间

wrap_content/match_parent有什么奥秘能够使视图的宽高灵活变化呢?

measureSpec影响宽高的计算

一个视图的绘制过程主要有三个部分:测量(measure),布局(layout)、绘制(draw)。其中测量过程就是计算一个视图宽高的过程,主要通过onMeasure方法实现。

 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 ...
}

onMeasure方法接收来至父视图对子视图宽高的约束measureSpec,具体的视图会根据measureSpec来计算视图的宽高。
measureSpec的一些概念:
measureSpec是一个32位的值,其前两位表示测量的模式,后30位表示测量的大小。
测量模式有三种:
EXACTLY:父控件给子控件决定特定的大小。
AT_MOST:子控件至多达到指定大小的值。
UNSPECIFIED:父控件没有对子控件施加任何约束,子控件可以得到任意想要的大小。
android提供了相应的方法来处理measureSpec

// 获取测量模式
int specMode = MeasureSpec.getMode(measureSpec);
// 获取测量大小
int specSize = MeasureSpec.getSize(measureSpec);
// 通过大小和模式生成measureSpec
MeasureSpec.makeMeasureSpec(resultSize, resultMode);

例如 TextView的onMeasure实现:

// onMeasure的关键实现
 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            width = widthSize;
        } else {
           ...           
            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(widthSize, width);
            }
        }
        ...
        if (heightMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            height = heightSize;
            mDesiredHeightAtMeasure = -1;
        } else {
            ...
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(desired, heightSize);
            }
        }
        ...
        setMeasuredDimension(width, height);
    }

首先:
从父视图的约束measureSpec获得约束的模式specMode和约束的大小specSize。
其次:
如果模式为EXACTLY(父控件给子控件决定特定的大小),则TextView的宽高直接为父视图约束的宽高;
如果模式是AT_MOST(子控件至多达到指定大小的值),则取TextView自身大小与父视图约束大小的最小值;
如果为UNSPECIFIED(父控件没有对子控件施加任何约束,子控件可以得到任意想要的大小),TextView没有额外处理就是取TextView自身的大小。
因此,视图宽高的计算是由父视图传递的约束measureSpec决定的。

那么measureSpec又是怎么来的呢?

wrap_content/match_parent影响measureSpec的计算

父视图在自己测量时会调用子视图的onMeasure方法,测量子视图
例如下面的一个布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>

其测量的时序图:


image.png

在measureChildWithMargins方法中调用了子视图的measure方法,最终执行了子视图的onMeasure方法。

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

而子视图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;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);

在getChildMeasureSpec方法中终于见到了久违的wrap_content\match_parent,可以看出子视图的measureSpec由两部分决定,父视图的measureSpec和子视图的LayoutParams。

如果子视图的LayoutParams宽高设置的是具体的大小

...
if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
} 
...

那么子视图meauserSpec约束模式就是EXACTLY,约束大小就是LayoutParams中定义的大小,根据前面介绍的TextView的onMeasure方法逻辑,计算出的大小就是约束的大小。

如果父视图约束的模式是EXACTLY(通常为父视图的宽高定义为具体大小),子视图LayoutParams中定义的是match_parent(占满父视图)

...
 case MeasureSpec.EXACTLY:
  if (childDimension == LayoutParams.MATCH_PARENT) {
          // Child wants to be our size. So be it.
          resultSize = size;
          resultMode = MeasureSpec.EXACTLY;
  } 
...

得到的子视图的measureSpec约束模式还是EXACTLY,约束大小为父视图约束的大小,TextView计算的宽高则与父视图一样大,实现占满父视图的效果;

如果子视图定义为wrap_content

...
 case MeasureSpec.EXACTLY:
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;
}
...

得到的子视图的measureSpec约束模式为AT_MOST,约束大小为父视图约束的大小,TextView计算的宽高则是自身大小与父视图约束大小的最小值一样大,实现由自身大小决定宽高,但不会超过父视图约束大小的效果。

还有很多种组合方式,就不一一列举,可以看到我们平常记忆理解的wrap_content\match_parent灵活变化视图宽高的作用效果,正是主要通过这段代码逻辑实现的。

理解视图测量时的一些疑问:

顶层视图的measureSpec的由来

从前面的讨论可以知道,测量方法的参数measureSpec都是由父视图传递进来的,那么最顶层的视图的measureSpec是从哪来的?

我们经常给activity设置的layout布局的根视图并非是最顶层视图。
先看一张图:


image.png

content部分为给activity设置的布局,其外层还有一个视图DecorView,这个才是最顶层视图。
而DecorView的测量过程是在ViewRootImpl的performTraversals方法中

private void performTraversals() {
    ...
    //获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示  DecorView根布局宽和高
    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

    // Ask host how big it wants to be
    //执行测量操作
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    ...
    //执行布局操作
    performLayout(lp, desiredWindowWidth, desiredWindowHeight);
    ...
    //执行绘制操作
    performDraw();
    ...
}

通过getRootMeasureSpec方法创建了DecorView的测量规格,在performMeasure方法中执行了DecorView的测量,遍历整个子视图。
并且视图的布局(layout)和绘制(draw)也是从这里发起的,通过先后执行performMeasure、performLayout、performDraw方法,完成整个页面的绘制过程

ListView对子视图测量的区别

ListView的子视图布局高度无论是设置wrap_content还是match_parent,其高度都为子视图自身的大小,这又是为什么呢?
ListView的中对子视图的测量调用的是其自己定义的方法measureScrapChild

private void measureScrapChild(View child, int position, int widthMeasureSpec, int heightHint) {
       LayoutParams p = (LayoutParams) child.getLayoutParams();
        ...
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeSafeMeasureSpec(heightHint, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
        ...
}

当子视图的高度设置为wrap_content或match_parent时,生成的子视图测量模式都是UNSPECIFIED,因此最终计算出的高度还是子视图自身的高度。

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

推荐阅读更多精彩内容