什么是LayoutInflater
LayoutInflater是一个用于将xml布局文件加载为View或者ViewGroup对象的工具,我们可以称之为布局加载器
用法
获取LayoutInflater的三种方法
1.LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
2.LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
3.LayoutInflater inflater = LayoutInflater.from(context);
通过源码发现,三个方法的本质都是调用了第2个方法,所以本质没有区别
LayoutInflater.inflate()方法
分为两种构造方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
例子:
inflater.inflate(R.layout.item_list, null); //子布局最外层的所有layout属性都失效 显示布局变成”wrap_content”
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。
参考链接:https://blog.csdn.net/u012702547/article/details/52628453