关于LayoutInflater的总结

首先先看一下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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值