LayoutInflater的inflate方法重载了四种调用方式,分别为:
public View inflate(int resource, ViewGroup root)
public View inflate(int resource, ViewGroup root, boolean attachToRoot)
public View inflate(XmlPullParser parser, ViewGroup root)
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
参数attachToRoot, 是否将载入的视图绑定到根视图中,即是否把选取的视图加入到root中。false 的意思就是不添加到root中。可能需要我们手动添加。
Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
inflate()常用方法为:
1.View.inflate(mContext, R.layout.xxx_layout, null);
2.LayoutInflater.from(mContext).inflate(R.layout.xxx_layout, null);
3.LayoutInflater.from(mContext).inflate(R.layout.xxx_layout, parent, false);
1调用2,2调用3。2和3的区别主要在:采用方式2填充视图,item布局中的根视图的layout_xxx属性会被忽略掉,然后设置成默认的包裹内容方式,如果我们想保证item的视图中的参数不被改变,我们需要方式3进行视图的填充。或者设置item布局的根视图为包裹内容,然后设置内部控件的高度等属性,这样用方式2填充视图就ok了。
推荐使用方式3!
参考: