版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wtu178/article/details/70049316
一般我们都是用:
inflater.inflate(R.layout.fragment_baby_list, null);来加载一个布局
分析:View.inflate()方法,看源码
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
得:View.inflate也是调用LayoutInflater.inflate()方法
继续看LayoutInflater.inflate()方法源码
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
按我们此调用方式:
inflater.inflate(R.layout.fragment_baby_list, null);
那调用方式就是:return inflate(resource, root, false);继续往下看:
源码:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);//调用XML文件
try {
return inflate(parser, root, attachToRoot);//看此方法
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
.......
View result = root;
.........
//重点
// 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;
}
........
return result;
}
总结:
如果设置了ViewGroup root参数,并且attachToRoot为true的话,则将我们加载的视图作为子视图添加到root视图中。
如果我们ViewGroup root设置为空的话,就直接返回我们创建的视图。
如果root不为空,并且attachToRoot为false的话,也返回我们创建的视图
当我们在ListView或者recyclerview的adapter设置成
mLayoutInflater.inflate(R.layout.bond_lot_detail_item, parent, true)或者mLayoutInflater.inflate(R.layout.bond_lot_detail_item, parent)就会有意想不到的报错。
至于为什么,可以去尝试一下,就明白了