深入理解LayoutInflater.inflate()

LayoutInflater的使用

形如 LayoutInflater.from(context).inflate(R.layout.test,root,true) 的使用在android开发中很常见,但许多人不但不清楚LayoutInflater的inflate()方法的细节,而且甚至在误用它。

这里的困惑很大程度上是因为Google上有关attachToRoot(也就是inflate()方法第三个参数)的文档太模糊。其实第三个参数的意思是:

如果attachToRoot是true的话,那第一个参数的layout文件就会被填充并附加在第二个参数所指定的ViewGroup内。方法返回结合后的View,根元素是第二个参数ViewGroup。如果是false的话,第一个参数所指定的layout文件会被填充并作为View返回。这个View的根元素就是layout文件的根元素。不管是true还是false,都需要ViewGroup的LayoutParams来正确的测量与放置layout文件所产生的View对象。

attachToRoot是True

假设我们在XML layout文件中写了一个Button并指定了宽高为match_parent。

1
2
3
4
5
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

现在我们想动态地把这个按钮添加进Fragment或Activity的LinearLayout中。如果这里LinearLayout已经是一个成员变量mLinearLayout了,我们只需要通过如下代码达成目标:

1
inflater.inflate(R.layout.custom_button, mLinearLayout, true);

下面的代码也有同样的效果。LayoutInflater的两个参数的inflate()方法自动将attachToRoot设置为true。

1
inflater.inflate(R.layout.custom_button, mLinearLayout);

另一种在attachToRoot中传递true的情况是使用自定义View:

1
2
3
4
5
6
7
public class MyCustomView extends LinearLayout {
...
private void init() {
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.view_with_merge_tag, this);
}
}

这个例子中layout文件没有ViewGroup作为根元素,所以我们指定我们自定义的LinearLayout作为根元素。如果layout文件有一个FrameLayout作为根元素,那么FrameLayout和它的子元素都可以正常填充,而后都会被添加到LinearLayout中,LinearLayout是根ViewGroup,包含着FrameLayout和其子元素。

attachToRoot是False

在这种情况下,inflate()方法中的第一个参数所指定的View不会被添加到第二个参数所指定的ViewGroup中。
当attachToRoot为false时,我们仍可以将Button添加到mLinearLayout中,但是这需要我们自己动手:

1
2
Button button = (Button) inflater.inflate(R.layout.custom_button, mLinearLayout, false);
mLinearLayout.addView(button);

这两行代码与刚才attachToRoot为true时的一行代码等效。通过传入false,我们告诉LayoutInflater我们不暂时还想将View添加到根元素ViewGroup中,意思是我们一会儿再添加。在这个例子中,一会儿再添加就是在inflate()后调用addView()方法。

在将attachToRoot设置为false的例子中,由于要手动添加View进ViewGroup导致代码变多了。将Button添加到LinearLayout中还是用一行代码直接将attachToRoot设置为true简便一些。

attachToRoot必须传入false的情况:
每一个RecyclerView的子元素都要在attachToRoot设置为false的情况下填充。这里子View在onCreateViewHolder()中填充

1
2
3
4
5
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(android.R.layout.list_item_recyclerView, parent, false);
return new ViewHolder(view);
}

RecyclerView负责决定什么时候展示它的子View,这个不由我们决定。在任何我们不负责将View添加进ViewGroup的情况下都应该将attachToRoot设置为false。

当在Fragment的onCreateView()方法中填充并返回View时,要将attachToRoot设为false。如果传入true,会抛出IllegalStateException,因为指定的子View已经有父View了。你需要指定在哪里将Fragment的View放进Activity里,而添加、移除或替换Fragment则是FragmentManager的事情:

1
2
3
4
5
6
7
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.root_viewGroup);
if (fragment == null) {
fragment = new MainFragment();
fragmentManager.beginTransaction().add(R.id.root_viewGroup, fragment).commit();
}

上面代码中root_viewGroup就是Activity中用于放置Fragment的容器,它会作为inflate()方法中的第二个参数被传入onCreateView()中。它也是你在inflate()方法中传入的ViewGroup。FragmentManager会将Fragment的View添加到ViewGroup中,你可不想添加两次。

1
2
3
4
5
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, parentViewGroup, false);
return view;
}

问题是:如果我们不需在onCreateView()中将View添加进ViewGroup,为什么还要传入ViewGroup呢?为什么inflate()方法必须要传入根ViewGroup?
原因是及时不需要马上将新填充的View添加进ViewGroup,我们还是需要这个父元素的LayoutParams来在将来添加时决定View的size和position。

下面是一种没有ViewGroup作为root传入inflate()方法的情况。当为AlertDialog创建自定义View时,还无法访问父元素:

1
2
3
4
5
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
View customView = inflater.inflate(R.layout.custom_alert_dialog, null);
...
dialogBuilder.setView(customView);
dialogBuilder.show();

在这种情况下,可以将null作为root ViewGroup传入。后来我发现AlertDialog还是会重写LayoutParams并设置各项参数为match_parent。但是,规则还是在有ViewGroup可以传入时传入它。

attachToRoot属性要点

  • 如果可以传入ViewGroup作为根元素,那就传入它。
  • 避免将null作为根ViewGroup传入。
  • 当我们不负责将layout文件的View添加进ViewGroup时设置attachToRoot参数为false。
  • 不要在View已经被添加进ViewGroup时传入true。
  • 自定义View时很适合将attachToRoot设置为true。

LayoutInflater实现原理

LayoutInflater的获取

LayoutInflater有两种写法,分别为:

1
LayoutInflater mLayoutInflater = LayoutInflater.from(context);

或者:

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

其实,第一种是第二种的简单写法,只是android给我们做了一下封装而已。具体可以查看源码

1
2
3
4
5
6
7
8
9
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;
}

得到LayoutInflater的实例后,我们就可以通过调用它的inflate()方法来加载布局了
其实LayoutInflater是一个抽象类:

1
2
3
public abstract class LayoutInflater {
....
}

既然是抽象类,那么一定有它的实现,我们知道系统会在ContextImpl中将所有的系统service,注入到ServiceFetcher中,关于”LAYOUT_INFLATER_SERVICE”有如下实现:

1
2
3
4
5
6
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});

关于通过Context(实现类ContextImpl)获取系统服务的流程请移步下面链接中getSystemService()的实现:
传送门:设计模式之单例模式及在Android源码中的应用

从上面代码可以知道LayoutInflater的实现类其实就是PhoneLayoutInflater,下面我们看看PhoneLayoutInflater的源码:

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
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
....
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
// 核心代码就是调用LayoutInflater的createView方法,根据传入的控件名称name以及sClassPrefixList的构造对应的控件
// 比如name是Button,则View就是android.widget.Button
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
}
}
return super.onCreateView(name, attrs);
}
....
}

具体看下LayoutInflater#createView方法:

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
// 根据完整路径的类名根据反射构造对应的控件对象
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 从缓存中获取当前控件的构造方法
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
// 如果缓存中没有,则获取当前控件全类名对应的Class,并且缓存其构造方法到sConstructorMap集合中
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
......
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通过反射构造当前view对象
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (Exception e) {
....
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}

LayoutInflater#createView方法比较简单,主要做了下面两件事:

  1. 从sConstructorMap集合中获取当前View对应的构造方法,如果没有则根据当前全类名创建构造方法,并且存入sConstructorMap缓存中。
  2. 根据构造方法,创建对应的View对象

LayoutInflater.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
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
....
// 通过传递的布局id,创建一个XmlResourceParser对象
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
/**
*
* @param parser xml解析器
* @param root 需要解析布局的父视图
* @param attachToRoot 是否将解析的视图添加到父视图
* @return
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
// Context对象
mConstructorArgs[0] = inflaterContext;
// 存储当前父视图
View result = root;
try {
......
final String name = parser.getName();
// 1.解析merge标签
if (TAG_MERGE.equals(name)) {
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 {
// 2.通过xml的tag解析layout的根视图,比如LinearLayout
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// 生成布局参数
params = root.generateLayoutParams(attrs);
// 3. 如果attachToRoot是false,表示不添加当前视图到父视图中,那么将params设置到自己的布局参数中
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 4. 解析temp视图中的所有子view
rInflateChildren(parser, temp, attrs, true);
// 如果root不是null,并且attachToRoot是true,那么将temp添加到父视图中,并设置对应的布局参数
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root是null,并且attachToRoot是false,那么返回的结果就是temp
if (root == null || !attachToRoot) {
result = temp;
}
}
}
....
return result;
}

上述inflate方法主要做了下面的操作:

  1. 单独解析merge标签,rInflate会将merge标签下的所有子View直接添加到根标签中
  2. 通过createViewFromTag方法解析普通元素
  3. 根据root和attachToRoot的状态,决定是否添加当前View对象到父视图中
  4. 解析temp视图中的所有子view

了解merge标签传送门:Android里merge和include标签的使用

createViewFromTag方法解析普通元素:
可以看到,通过inflate加载视图中,解析单个元素的createViewFromTag是很常用的,下面先看看createViewFromTag方法:

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
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
try {
View view;
// 用户可以通过设置LayoutInflater的factory自行解析,如果没有设置则默认为null,所以这可以忽略这段
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
.....
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
// 这里是android内置的View控件,由于android自带的View控件,我们在使用的时候不需要全类名,所以这里是-1
view = onCreateView(parent, name, attrs);
} else {
// 自定义View控件的解析,自定义View必须写View的完整类名,比如"<com.xx.SelfView/>"
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
}
//省略catch代码
}

我们知道对于系统自带的View会走到onCreateView方法创建,前面的分析已经知道当我们使用LayoutInflater的时候,其实是使用其实现类PhoneLayoutInflater,它复写了onCreateView方法,在该方法里同样会通过createView这样的方法创建对应的View对象,并且传入”android.widget.”这样的包名,这就是为什么我们使用系统自带的View控件时候,不需要写全类名的原因。

rInflateChildren方法解析所有子元素:
在LayoutInflater#inflate方法中,当解析完根视图以后,会通过rInflateChildren解析当前根视图下的所有子视图

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
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
//获取树的深度,深度优先遍历
final int depth = parser.getDepth();
int type;
//挨个元素解析
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) { // 解析include标签
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 递归调用进行解析,并且将解析出的View添加到其父视图中
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}

可以看到rInflate中,rInflate通过深度优先遍历来构造视图树,每次解析到一个View元素就会递归调用,知道该路径下的最后一个元素,然后在回朔回来将每个View元素添加到他们对应的parent中,通过rInflate解析完成以后,整棵View结构树就构建完成了。

递归的原理也很简单,终止条件是type==XmlPullParser.END_TAG。接下来,举一个简单的例子,来模拟一下LayoutInflater.inflate函数生成View数的过程:

1
2
3
4
5
6
7
8
<RelativeLayout>
<ImageView1 />
<TextView1 />
<LinearLayoyt>
<ImageView2 />
<TextView2 />
</LinearLayout>
</RelativeLayout>

依据inflate方法的流程:

  1. 函数首先通过最初的Tag创建了RelativeLayout的View。然后调用了rInflate方法,传入的参数为(parser, parent=RelativeLayout, attrs);
  2. 进入到rInflate方法后,由于ImageView1和TextView1没有子结构,所以递归调用rInflate的时候会遇到type==XmlPullParser.END_TAG的终止条件,因此这两个View都被add到了RelativeLayout上。
  3. 但是,继续向下解析的时候,到LinearLayout就不一样了。LinearLayout递归调用rInflate的时候,会把自己作为parent传入,导致解析ImageView2和TextView2的时候,均为add到LinearLayout上。最后,LinearLayout再被add到最外层root节点RelativeLayout上。

附上Activity界面加载显示后的View树: