0%

LayoutInflater#inflate方法参数的作用

日常开发中很多地方都见到了LayoutInflater.from().inflate()方法去将一个布局文件的内容填充为一个View,特别是inflate()这个方法,这个方法的参数有布局文件id,root和attachToRoot,那么这个root和attachToRoot参数有什么作用呢?

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
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {  
synchronized (mConstructorArgs) {

View result = root;

try {
advanceToRootNode(parser);
final String name = parser.getName();

if (TAG_MERGE.equals(name)) {
// merge标签处理
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
final View temp = createViewFromTag(root, name, inflaterContext, attrs);

ViewGroup.LayoutParams params = null;

if (root != null) {
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
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) {
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) {
result = temp;
}
}

} catch (XmlPullParserException e) {

} catch (Exception e) {

} finally {
// Don't retain static reference on context.

}

return result;
}
}

分析root与attachToRoot的四种组合情况,可以得出以下结论:

root null null not null not null
attachToRoot true false true false
返回创建的不会带params的view,不作为root的子view 创建出来的View没有设置params就使用,所以被创建出来的布局,最外层设置的宽高是无效的,并最终返回了创建出来的View对象 view带param添加到root中,返回root 返回创建的带params的view,不作为root的子view
  • root = null,无论attachToRoot取什么值都是一样的效果