一、概述
将布局XML布局文件实例化为其对应的View
对象,可以称为布局加载器。在Fragment的onCreateView方法、ListView Adapter的getView方法等许多地方都可以见到它的身影。
二、使用
1、获取实例
第一种:
LayoutInflater layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第二种:
LayoutInflater layoutInflater= LayoutInflater.from(context);
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
第三种:
在Activity内部调用getLayoutInflater()方法
第二种和第三种都是通过封装后的方法调用getSystemService
2、加载布局
第一种:
layoutInflater.inflate(resourceId, root);
inflate()方法一般接收两个参数,第一个参数就是要加载的布局id,第二个参数是指给该布局的外部再嵌套一层父布局,如果不需要就直接传null。这样就成功成功创建了一个布局的实例,之后再将它添加到指定的位置就可以显示出来了。
第二种:
inflate(int resource, ViewGroup root, boolean attachToRoot)
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。(root只是用来参与布局根View的大小、位置设置的)
4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。