LJ的Blog

学海无涯苦做舟

0%

View的工作流程——measure

写在前面

今天和老爸去医院了,老爸最近腰疼,幸好没什么事,各位也要多多爱惜自己的身体,等身体出了问题就来不及了。好了,闲话到此为止,话说《开发艺术探索》里面不少东西我早就看了,但是因为自己当时水平有限,而且有很多也看不大懂,所以看了忘是挺正常的事。不过感觉随着工作经验的增长,以前大学里上过《操作系统》、《计算机网络》、《数据结构》等一些课都被串到了一起,感觉很好,而且愈发能感觉到自己的不足了。这周的文主要算是一篇读书笔记吧,记一下读《开发艺术探索》第四章和View相关的笔记,至于ViewGroup我觉得还需要过段时间,在沉淀一下再来和各位一起探索一下。而且说真的,这篇文我也是硬着头皮写下来的,因为看源码看着看着发现我疑问越来越多,很多都是现阶段暂时无法解决的,不过问题总是一个一个去解决的,先过一遍View的measure流程再说其他的。

ViewRoot & DecorView

ViewRoot对应于ViewRootImpl类,在ViewRootImpl类中有如下一段注释:

1
2
3
4
/** 
* The top of a view hierarchy, implementing the needed
* protocol between View and the WindowManager.
*/

View层最顶部,实现了View和WindowManager间所需的协议。这个类很重要,但是我现在对其理解也不是很深(一是因为读源码无力,一是没有系统的阅读过源码),所以就拿书上的话来说:它是连接WindowManager和DecorView的纽带,View的三大流程均是通过ViewRoot来完成的。在ActivityThread中(同样很有意思的一点是ActivityThread是一个类,并非线程什么的,当然了如果哪一天我读通了这一块回来和各位分享的),当Activity对象被创建完毕后,会将DecorView添加到Window中,同时会创建ViewRootImpl对象,并将ViewRootImpl对象和DecorView建立关联。

接下来直接放结论,尽快进入正题:
View的绘制流程是从ViewRoot的performTraversals开始的,它经过measure、layout和draw三个过程才能最终将一个View绘制出来。

MeasureSpec

在之前Android自定义View你需要知道的一些东西中我已经简要的介绍过MeasureSpec了,当然在这不敢再麻烦各位去看了,继续简介一下,熟悉的可以跳过这段。

首先咱直接看他的注释,看看注释是怎么解释这玩意的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* A MeasureSpec encapsulates the layout requirements passed from parent to child.
* Each MeasureSpec represents a requirement for either the width or the height.
* A MeasureSpec is comprised of a size and a mode. There are three possible
* modes:
* <dl>
* <dt>UNSPECIFIED</dt>
* <dd>
* The parent has not imposed any constraint on the child. It can be whatever size
* it wants.
* </dd>
*
* <dt>EXACTLY</dt>
* <dd>
* 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.
* </dd>
*
* <dt>AT_MOST</dt>
* <dd>
* The child can be as large as it wants up to the specified size.
* </dd>
* </dl>
*
* MeasureSpecs are implemented as ints to reduce object allocation. This class
* is provided to pack and unpack the <size, mode> tuple into the int.
*/

最上面那段话的大概意思是一个MeasureSpec封装了一个从父(控件)传给子(控件)的布局要求。每个MeasureSpec代表的不是宽就是高的要求。一个MeasureSpec包含了一个尺寸和一个(测量)模式,这些模式如下:

  • UNSPECIFIED
    父(容器)对子(控件)没有任何限制,子控件可以想要多大就有多大。

  • EXACTLY
    父容器已经决定了子控件的精确尺寸,子控件将会变成被给出的约束大小,不管他自己想要变成啥样。

  • AT_MOST
    子控件可以和和他想要的规格尺寸一样大。

最后一段话解释了一下为什么这么实现,暂时不需要咱关心这些。看完了注释基本上已经对MeasureSpec有了一个基本的认识了。但是看完这段注释,应该会产生一个疑惑,在注释中说MeasureSpec是父传递给子的,那么最顶层的DecorView的MeasureSpec是如何来的呢?《开发艺术探索》上说是在ViewRootImpl的measureHierarchy方法中创建的,主要代码如下:

1
2
3
childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth,lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight,lp.width);
performMeasure(childWidthMeasureSpec,childHeightmeasureSpec);

其中desiredWindowWidth和desiredWindowHeight就是屏幕的尺寸,追踪下getRootMeasureSpec()源码看看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}

可以看到该方法中对于match_parent、wrap_content和其余情况的处理:

  • LayoutParams.MATCH_PARENT:采用精确模式测量,大小是窗口大小

  • LayoutParams.WRAP_CONTENT:大小不定,最大是窗口大小

  • 其他:结合我们平时写xml和代码的经验,此处其他应该就是我们制定了大小(比如100dp),大小为指定大小。

View的MeasureSpec的获取

上面的MeasureSpec注释里说了,是从父传递到子的,那么View很明显是一个子布局,让我们上ViewGroup里找找child是如何获取MeasureSpec的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Ask all of the children of this view to measure themselves, taking into
* account both the MeasureSpec requirements for this view and its padding.
* We skip children that are in the GONE state The heavy lifting is done in
* getChildMeasureSpec.
*
* @param widthMeasureSpec The width requirements for this view
* @param heightMeasureSpec The height requirements for this view
*/
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);
}
}
}

老规矩,先让我这个渣渣来翻译一下注释……
遍历View去测量他们自身,既要考虑MeasureSpec的要求又要考虑padding。跳过GONE状态的(不测量这个状态的View),更繁重的事在getChildMeasureSpec完成。

很明显,咱得看一下getChildMeasureSpec方法了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Does the hard part of measureChildren: figuring out the MeasureSpec to
* pass to a particular child. This method figures out the right MeasureSpec
* for one dimension (height or width) of one child view.
*
* The goal is to combine information from our MeasureSpec with the
* LayoutParams of the child to get the best possible results. For example,
* if the this view knows its size (because its MeasureSpec has a mode of
* EXACTLY), and the child has indicated in its LayoutParams that it wants
* to be the same size as the parent, the parent should ask the child to
* layout given an exact size.
*
* @param spec The requirements for this view
* @param padding The padding of this view for the current dimension and
* margins, if applicable
* @param childDimension How big the child wants to be in the current
* dimension
* @return a MeasureSpec integer for the child
*/
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);
}

咱继续翻译一下……
困难的事咱来做:算出MeasureSpec传递给
一个child。这个方法为一个子view的一个尺寸(高或宽)算出正确的MeasureSpec。

他的目的是组合MeasureSpec和LayoutParams的信息让child获取最好的可能结果。例如:如果这个view知道他的尺寸(因为测量模式是EXACTLY),这个child已经指出了他的LayoutParams,他想和他的父容器有一样的尺寸(match_parent),这时父容器应该要求child布局成被给的精确尺寸。

从上面的注释我们可以了解到,子View的MeasureSpec并不是由其自身的LayoutParams决定的,而是由其父容器和其自身的LayoutParams一同决定的。接下来看一下代码,看看究竟是怎么操作的:

  • 首先从ViewGroup的宽/高的MeasureSpec中获取到对应的specMode,然后根据不同的mdoe去执行不同的操作

  • EXACTLY:如果子View指定了精确值的大小,那么测量模式是EXACTLY,尺寸是传入的childDimension,这两个值将会被打包成一个MeasureSpec并返回。如果childDimension等于MATCH_PARENT,那么就将上面获取到的自身尺寸和EXACTLY模式打包成一个MeasureSpec打包并返回。如果childDimension等于WRAP_CONTENT,那么将自身尺寸赋给孩子的尺寸,让子View的尺寸不要大于父容器就行了,将这个尺寸和AT_MOST模式打包并返回。

之后的AT_MOST和UNSPECIFIED测量模式和EXACTLY的套路差不多,就不一一看过去了,《Android开发艺术探索》上总结了一个表格:

|columns:childLayoutParams/rows:parentSpecMode|EXACTILY|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|

最后要强调一句和《开发艺术探索》上一样的话,以上的表格并非是经验总结,而是将代码具现为一个表格罢了。

View的measure流程

终于填完了几个比较重要的坑,可以来讲讲View的measure流程了。View的测量是由measure()方法实现的 ,在measure()方法中会去调用onMeasure()方法,看一下View的onMeasure()方法的实现:

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

关于这个方法有一些要注意的地方,在以前的Android自定义View你需要知道的一些东西都有说过,而且这个方法的注释里都有写你需要注意的东西,感兴趣的可以去看看,这里就不赘述了。以上方法调用了setMeasuredDimension方法设置View宽高,因此我们看一下他是如何获取宽高的就可以了,不多说,看源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}

看得出来,这里只是进行了一些简单的判断和赋值操作,如果测量模式是AT_MOST和EXACTLY:那么就返回View测量后的大小,如果是UNSPECIFIED模式那么就返回传入的size值。接下来看看传入的这个size值是怎么获取的:

1
2
3
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

从以上代码我们可以看出,如果view有背景则从最小宽度和background的宽度中返回较大的那个,如果没有背景则返回最小宽度,这个最小宽度我们可以通过xml或者setMinimumWidth来设置,默认为0。

接下来通过一个问题来回忆一下今天所了解的东西:在View中使用wrap_content为什么效果和match_parent效果一样?
首先这个问题需要去ViewGroup里看看,因为View的MeasureSpec是从ViewGroup中传递而来的,前面我们画的那张表格就是处理代码的具现,我们可以直接查表~

查表可知在match_parent和wrap_content这两种情况下传递给View的size都是parentSize(忽略UNSPECIFIED的情况),那么再看看View有没有对这两种情况做特殊的处理就行了。而在上面的getDefaultSize方法里可以看到AT_MOST和EXACTLY两种模式返回值都是相同的,因此在自定义继承于View的控件时需要我们去重写onMeasure()方法来处理wrap_content的情况。

读到这你可能会发现View和ViewGroup这俩货根本分不开,事实也是如此,但是在这我就不继续记我的笔记了,因为有些事我也没想明白,所以留待以后填坑吧(立了个flag)。

后记

还有一个ViewGroup的measure流程这里并没有继续了,想留着以后再来填这个坑吧。记得原来读《Android开发艺术探索》都是:“哦,原来是这样的” 状态,现在读则是会对一些代码的流程产生疑惑,而这些疑惑以我现在水平还是有些难以解决的。不过学习就是不断完善和不断有新的问题的过程,如同我们初中高中所学的物理一样,很多时候我们学到的只是相对正确的知识,但是在以后不断学习的过程中,我们可以不断的纠正自己以前的错误和带有局限的理解。