使用LayoutInflater的理解

今天封装xml布局到view的时候遇到了内容直接变成包裹内容,显示与写的布局不符合的情况,检查后发现是LayoutInflater使用错误的问题,因此这里今天就记录一下LayoutInflater的部分理解。

LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;类似findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等),并且实例化。

获得 LayoutInflater 实例的三种方式

1.LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()

2.LayoutInflater localinflater =(LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);

3.LayoutInflater inflater = LayoutInflater.from(context);

研究源码可以看到 getLayoutInflater() 中调用了 LayoutInflater.from(context), 而LayoutInflater.from(context) 中又调用了(LayoutInflater)context.getSystemService 所以可以知道,三种调用方式本质是没有区别的。

造成我的布局问题的就是下边LayoutInflater的inflate方法,
1、inflate(int resource, ViewGroup root) 2、inflate(int resource, ViewGroup root, boolean attachToRoot) 常用的这两种调用方式,root如果传递的是null引入的resource布局中设置的长宽等属性都会变成默认包裹内容(wrap_content),所以有设置布局别的属性的话在root的地方传递一个ViewGroup。

inflater.inflate(R.layout.item_list, null); —-> 显示布局变成默认包裹内容

inflater.inflate(R.layout.item_list, parent,false);—–> 正常显示布局

借鉴别人的理解:
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值