0%

Android LayoutInflater理解

LayoutInflater,布局填充器,把XML布局文件实例化为相应的View。Android开发者对LayoutInflater都已经很熟悉了。但是究竟它是如何做到的呢?让我们来简单探究一下主要流程。

LayoutInflater实例

先看一下LayoutInflater实例的创建

1
LayoutInflater inflater = LayoutInflater.from(context);

或者

1
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其实这两种写法效果完全一样,只不过Android给我们简单封装一下。LayoutInflater.from()的源码如下:

1
2
3
4
5
6
7
8
9
10
11
/**
* Obtains the LayoutInflater from the given context.
*/
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}

inflate加载布局文件

得到了LayoutInflater的实例之后就可以调用它的inflate()方法来加载布局了,可以使用两个参数的方法,也可以用三个参数的 如下所示:

1
2
View view = inflater.inflate(R.layout.button_layout, null);
View view = inflater.inflate(R.layout.button_layout, mainLayout, false);

这两种又有什么区别呢?我们查看两个参数的方法可以看到:
1
2
3
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}

1
2
3
4
5
6
7
8
9
10
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();

final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}

当我们调用inflate(int resource, ViewGroup root)时,系统会根据你传入的root是否为空设置默认值。如果root为null则attachToRoot为false,root不为null时attachToRoot为true。在inflate中才调用了真正的inflate去解析XML填充为View。inflate源码如下:

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
88
89
90
91
92
93
94
95
96
97
98
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
// 先指定返回结果为root
View result = root;

try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}

// 如果 type != 开始节点抛出错误
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
// 获取当前节点的名字,也就是当前layout的根节点的名字
final String name = parser.getName();

...
// 处理 merge 节点
if (TAG_MERGE.equals(name)) {
// root必须非空且attachToRoot为true,否则抛异常结束
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}

rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
// 根据节点的名字与属性创建View,createViewFromTag里会调用createView方法,然后利用反射实例化view对象
final View temp = createViewFromTag(root, name, inflaterContext, attrs);

ViewGroup.LayoutParams params = null;

if (root != null) {
// Create layout params that match root, if supplied

// 把布局文件中layout属性读取出来
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
// attachToRoot为false 设置根视图的layout属性
temp.setLayoutParams(params);
}
}

// Inflate all children under temp against its context.
// 递归查找这个视图下所有子视图
rInflateChildren(parser, temp, attrs, true);

// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
// 把resource中根视图直接添加到root里,并设置根视图的layout属性
root.addView(temp, params);
}

// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
// 如果root为null,或者attachToRoot为false,result的值改为根视图
// 注意开始result的值是root,result为inflate方法最终返回的值
result = temp;
}
}

} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}

Trace.traceEnd(Trace.TRACE_TAG_VIEW);

return result;
}
}

总结:

  1. 如果root为null,不会去读取布局文件中的layout属性,所以layout属性无效。attachToRoot将失去作用,设置任何值都没有意义。
  2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
  3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
  4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

转载请注明出处:https://blog.lovek.vip/2016/10/20/android-LayoutInflater

赞赏是最好的支持