LayoutInflater.infalte(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)的返回值一定是 xml 中的 rootView 吗?
答案是否定的:
Returns View The root View of the inflated hierarchy. If root was
supplied and attachToRoot is true, this is root; otherwise it is the
root of the inflated XML file.
从该方法的doc中可以看到,如果 提供了root 且 attachToRoot为true,返回值是root, 否则,是xml 中的 root。
代码也很简单:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
调用的是 inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
View result = root;
try {
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 {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// 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) {
// ...
}
return result;
}
}