关于LayoutInflater的总结

来源:互联网 发布:股票交易系统测试软件 编辑:程序博客网 时间:2024/05/15 16:37

首先先看一下Android Studio Lint的警告:

      Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element) less... (Ctrl+F1)

When inflating a layout, avoid passing in null as the parent view, since otherwise any layout parameters on the root of the inflated layout will be ignored.     

所在代码是这样的:headerView= LayoutInflater.from(getContext()).inflate(R.layout.home_title,null);

这段警告意思很明了:如果第二个参数传null,那么layout的根部局的所有属性都被忽略。

inflate的几个重载函数:

1.inflate(@LayoutRes int resource, @Nullable ViewGroup root)
2.inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
3.inflate(XmlPullParser parser, @Nullable ViewGroup root)
4.inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
常用的是前两种方式,通过源码:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {    return inflate(resource, root, root != null);}
可知,最后调用的还是三个参数的方法inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
那么我们常用的就四种组合
1.inflate(R.layout.item,null,false); 通过源码可知这种形式相当于inflate(R.layout.itemnull)
root为空,会导致R.layout.item的根布局失效,如果用在ListView或者RecyclerView的布局中会为达到效果,需要内嵌一个布局,这样就造成了根布局的冗余;
2.inflate(R.layout.item,null,true);
不管true或者false,都要手动添加布局到root上。
3.inflate(R.layout.item,root,false);
item的根布局有效,因为attachToRoot为false,需要手动添加item到root上。
4.inflate(R.layout.item,root,true);
item的根布局有效,因为attachToRoot为true,inflate会自动添加item到root上。



0 0