LayoutInflater.from(this).inflate()参数解析

来源:互联网 发布:中船重工 知乎 编辑:程序博客网 时间:2024/06/05 10:35
LayoutInflater.from(this).inflate(layoutId, root, boolean);LayoutInflater.from(this).inflate(layoutId, root);


布局填充器,填充布局时,不同参数会有不同的反差效果。很郁闷,怎么不是我想要的?
很久以前深入理解过,又总是忘记。下面已我自己的理解方式记录下来,便于日后速查。
网上大神有总结:
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。




绝对精辟,我相信。但不满足于此。
我关心的是:
1、当前的item局部是否添加到父容器中?
2、当前的布局跟容器宽高属性是否生效?
3、inflate()方法返回的是哪个容器?




做实验得出结论:


1、
返回的view是父容器布局(不是item布局的跟容器,如例中的root布局);
item跟布局的宽高属性生效(item布局的跟容器宽高属性生效);
已经添加到父容器中(item布局已经添加到root中了)。

RelativeLayout root = (RelativeLayout) findViewById(R.id.other_layout);View view2 = LayoutInflater.from(this).inflate(R.layout.item, root, true);View view5 = LayoutInflater.from(this).inflate(R.layout.item, root);


2、
返回R.layout.item页面的跟布局(item跟布局);
跟布局的宽高属性生效;
未添加到父容器中。

RelativeLayout root = (RelativeLayout) findViewById(R.id.other_layout);View view1 = LayoutInflater.from(this).inflate(R.layout.item, root, false);


3、返回R.layout.item页面的跟布局;
跟布局的宽高属性失效(仅宽高属性失效,其他属性生效);
未添加到父容器中。

View view3 = LayoutInflater.from(this).inflate(R.layout.item, null, false);View view4 = LayoutInflater.from(this).inflate(R.layout.item, null, true);View view6 = LayoutInflater.from(this).inflate(R.layout.item, null);




阅读全文
0 0