目录
  1. 1. View 工作原理
    1. 1.1. View 绘制整体流程
    2. 1.2. Measure
      1. 1.2.1. MeasureSpec
      2. 1.2.2. MeasureSpec 和 Layoutparams 的对应关系
        1. 1.2.2.1. DecorView 的 MeasureSpec
        2. 1.2.2.2. 普通的 View 的 measure
      3. 1.2.3. measure 过程
        1. 1.2.3.1. 看 View 的 measure 过程
      4. 1.2.4. ViewGroup 的 measure 过程
    3. 1.3. Layout
    4. 1.4. draw
    5. 1.5. 自定义 view 须知
view工作原理

View 工作原理

首先先来说明一下要掌握的知识

  • View 绘制工作整体流程
  • Measure
  • Layout
  • Draw

View 绘制整体流程

View 的绘制是从 ViewRoot 的 performTraversals 方法开始的。

ViewRoot 的作用

对应与 ViewRootImpl 类,View 的三大流程都是通过 ViewRoot 来完成的。在 Activity 被创建后,会将 DecorView 添加到 Window 中,同时创建 ViewRoot 的对应类的对象和 DecorView 关联。

1
2
root = new ViewRootImpl(view.getContext() , display);
root.setView(view, wparams, panelParentView());

继续回到 View 绘制的入口,ViewRoot 的 performTraversals 方法。

大致流程如图
image

首先可以看出三大流程的调用顺序是measure-->layout-->draw

以 measure 为例,稍微说明。详细说明看下面的 measure 过程。
performTraversals 方法调用 ViewGroup 的 performMeasure 方法,performMeasure 调用 measure 方法,measure 方法又调用 onMeasure 方法,在 onMeasure 方法中,会遍历调用子 View 的 measure 方法,这样就完成了整个 View 树的遍历。

上面还提到了 DecorView,为什么在这里要提到 DecorView 呢?因为 DecorView 是顶级容器,View 层的事件都必须通过 DecorView 传给相应的 View。这也是 View 工作流程的一部分。

作为顶级容器,DecorView 是一个 FrameLayout,其中一般包含一个垂直的 LinearLayout(包含 TitleView 和 ContentView)。其中 contentView 的 id 是 R.android.content

Measure

MeasureSpec

MeasureSpec 是参与 view 的 measure 流程中的一个重要成员。

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


public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}

@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
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);
}
//省略代码..........
}

源码写的很清楚,MeasureSpec 主要管理一个 32 为的 int 类型的值,高两位代表 SpecMode,低 30 位代表 SpecSize。

SpecMode 有三种:

  • UNSPECIFIED
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;

    高 2 位为 00,表示父容器对 view 没有约束,要多大给多大。

  • EXACTLY
    public static final int EXACTLY = 1 << MODE_SHIFT;

    高 2 位为 01,表示父容器已经知道了 view 的大小,这时候 SpecSize 就是 view 的最终大小。对应 LayoutParams 中的 match_parent 和具体数值大小。

  • AT_MOST
    public static final int AT_MOST = 2 << MODE_SHIFT;

    高 2 位是 10,表示父容器会提供一个可用大小(SpecSize),view 的大小不能超过这个 SpecSize;,具体大小是多少要看不同 view 的具体实现。对应 LayoutParams 中的 wrap_content。

上面提到了 MeasureSpec 和 LayoutParams 的一些关系,下面来解析一下 LayoutParams 如何转换成对应的 MeasureSpec。

MeasureSpec 和 Layoutparams 的对应关系

我们给 view 设置大小通常是给 View 设置 LayoutParams,在 view 的测量过程中,系统会将 LayoutParams 在父容器的约束下转换成 MeasureSpec;这里 DecorView 和普通 View 的测量还有点不一样。DecorView 的 Measure 是由窗口尺寸和自身的 LayoutParams 决定的;而普通的 View 是由父容器的 MeasureSpec 和自身的 LayoutParams 决定的。Measure 确定后,就可以在 onMeasure 方法中获取 view 的测量宽高

DecorView 的 MeasureSpec

在 ViewRootImpl 里有这样一个方法measureHierarchy,里面有 DecorView 的 MeasureSpec 的创建过程。

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

desiredWindowWidth,desiredWindowHeight 就是屏幕的宽高。

再看看getRootMeasureSpec是怎么实现的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   private static int getRootMeasureSpec(int windowSize ,int rootDimension){
int measureSpec;
switch (rootDimension){

case ViewGroup.LayoutParams.MATCH_PARENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize ,MeasureSpec.EXACTLY);
break;

case ViewGroup.LayoutParams.WRAP_CONTENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize ,MeasureSpec.AT_MOST);
break;

default:
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension ,MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}

在这里可以看出 MeasureSpec 的 SpecMode 原来是从 LayoutParam 中得来的。

普通的 View 的 measure

之前说过 View 的 measure 过程;他是从 ViewGroup 中传递过来的。

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
/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding
* and margins. The child must have MarginLayoutParams The heavy lifting is
* done in getChildMeasureSpec.
*
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param widthUsed Extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec The height requirements for this view
* @param heightUsed Extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
*/
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);
}

首先获取到了 Childview 的 MarginLayoutparams,然后通过 getChildMeasureSpec 来获得子 view 的 MeasureSpec。然后将子 View 的 MeasureSpec 的数据传给子 View,接下来就是 ziView 的 measure 过程。getChildMeasureSpec 这个方法有好多参数。可以看到,子 view 的 MeasureSpec 的创建与父容器的 MeasureSpec 还有自身的 Layoutparams 有很大关系。下面就看一下 getChildMeasureSpec 如何得到子 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
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
87
/**
* 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;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

同样的来分析这个函数,和 DecorView 的 MeasureSpec 创建差不多。首先,通过父容器的 MeasureSpec 获取父容器的 SpecMode,和 SpecSize;
获取到 SpecSize 后会计算出留给子 View 的大小空间(非负)。根据父容器的 SpecMode 来计算子 View 的 MeasureSpec。有三种情况

  • 父容器的 SpecMode 是 MeasureSpec.EXACTLY:
    • 1.子 view 的 LayoutParams 对应的是一个具体数值,那这个具体数值就赋值给 resultSize(子 View 的 SpecSize);resultmode(子 View 的 SpecMode)因为是具体数值,所以就是 MeasureSpec.EXACTLY;
    • 2.子 view 的 LayoutParams 对应的是 LayoutParams.MATCH_PARENT,那就把父容器留给子 View 的大小空间 size 赋值给 resultSize(子 View 的 SpecSize);resultmode(子 View 的 SpecMode)因为是具体数值 size,所以就是 MeasureSpec.EXACTLY;
    • 3.子 view 的 LayoutParams 对应的是 LayoutParams.WRAP_CONTENT,那就把父容器留给子 View 的大小空间 size 赋值给 resultSize(子 View 的 SpecSize);resultmode(子 View 的 SpecMode)因为 LayoutParams.WRAP_CONTENT,所以就是 MeasureSpec.EXACTLY;
  • 父容器的 SpecMode 是 MeasureSpec.AT_MOST
    • 1…….
    • 2…….
    • 3…….
  • 父容器的 SpecMode 是 MeasureSpec.UNSPECIEFIED
    • 1…….
    • 2…….
    • 3…….

到这里已经介绍了 MeasureSpec。之后可以具体看看是如何通过 MeasureSpec 来得到 View 的测量大小。

measure 过程

view 的 measure 过程和 Viewgroup 的 measure 过程也不一样。

看 View 的 measure 过程

View 的 measure 方法是一个 final 类型的方法,所以不能被重写。measure 方法里面调用了 onMeasure 方法。

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

setMeasuredDimension 这个方法会设置 view 的测量值。这个测量值室友 getDefaultSize(int size, int measureSpec)方法得到。在看看 getDefaultSize 方法的代码

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
/**
* Utility to return a default size. Uses the supplied size if the
* MeasureSpec imposed no constraints. Will get larger if allowed
* by the MeasureSpec.
*
* @param size Default size for this view
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
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;
}

可以看到只有 SpecMode 为 UNSPECIFIED 的时候,getDefaultSize 的返回值才和 getSuggestedMinimumWidth()有关。这里不考虑,因为我们主要使用的是另外两种 AT_MOST 和 EXACTLY。这两种都是直接返回 SpecSize。要注意返回的是测量的大小,并不是最终的大小,最终的大小是在 layout 阶段完成的。 但是基本上测量的大小就是最终的大小。从上面的方法可以看出如果一个自定义控件直接继承 view,那就要重写 onMeasure 方法中 WRAP_CONTENT 的情况,因为从代码中可以看出当 view 的 LayoutParams 是 WRAP_CONTENT 时,自身的 SpecMode 就是 AT_MOST,那么他的 SpecSize 就是父容器剩余的大小,测量的大小也就是父容器剩余的大小。如果不重写,那么 WRAP_CONTENT 会出现和 MATCH_PARENT 一样的效果,大小为父容器剩余大小。

ViewGroup 的 measure 过程

ViewGroup 并没有重写自己的 onMeasure 方法,但是他提供了一个 measureChildren 方法。在这个方法里遍历对子 view 进行 measure,调用 measureChild 方法,这个方法在上面已经说过了。ViewGroup 没有具体的测量过程,因为这是一个抽象类,具体的测量过程通过子类重写 onMeasure 实现。可以看看 LinearLayout 怎么实现的。

Layout

Layout 是用来确定 ViewGroup 中子 View 的位置的,ViewGroup 的位置确定后,会遍历子 View 的 layout 方法。layout 会调用 onLayout 方法,这个方法 主要是确定子 View 在父容器中的位置。

image

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
/**
* Assign a size and position to a view and all of its
* descendants
*
*

This is the second phase of the layout mechanism.
* (The first is measuring). In this phase, each parent calls
* layout on all of its children to position them.
* This is typically done using the child measurements
* that were stored in the measure pass().


*
*

Derived classes should not override this method.
* Derived classes with children should override
* onLayout. In that method, they should
* call layout on each of their children.


*
* @param l Left position, relative to parent
* @param t Top position, relative to parent
* @param r Right position, relative to parent
* @param b Bottom position, relative to parent
*/
@SuppressWarnings({"unchecked"})
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}

int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;

boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
onLayout(changed, l, t, r, b);

if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}

mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLayoutChangeListeners != null) {
ArrayList listenersCopy =
(ArrayList)li.mOnLayoutChangeListeners.clone();
int numListeners = listenersCopy.size();
for (int i = 0; i < numListeners; ++i) {
listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
}
}
}

mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}

layout 过程比 measure 过程简单好多。

image

draw

主要是跟画布操作有关。。。

自定义 view 须知

  • 1.让 View 支持 wrap_content
  • 2.最好支持 padding
  • 3.不需要使用 handler 方法,因为 view 中提供了 post 方法
  • 4.view 消失时,需要及时停止 view 中的线程和动画
  • 5.处理好滑动冲突
文章作者: HenryHaoson
文章链接: https://henryhaoson.github.io/2017/06/15/2017-6-5-View%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HenryHaoson
打赏
  • 微信
  • 支付寶