1.概述
1.1 定义
加载布局的任务通常都是在Activity中调用setContentView()方法来完成的,其实setContentView()方法内部也是是由LayoutInflater来加载布局的。
LayoutInflater是一个抽象类,继承自Object,位于android.view包下,作用类似于findViewById(),但是不同的是,LayoutInflater找的是xml布局文件并且实例化,而finViewById()是找到具体的widget控件。
1.2 使用场景
动态的载入一个xml布局,将xml布局文件实例化为它对应的View对象,从而获取其中的控件。比如在ScrollView、ListView和RecycleView中,动态的加入子item。
2.创建
2.1 获取LayoutInflater实例
LayoutInflater这个类不能直接使用,即不能直接调用其成员,必须先获取其实例才能使用。获取实例的方法如下所示:
2.1.1 方式一
LayoutInflater inflater = getLayoutInflater(); //说明:getLayoutInflater()是Activity类中的方法,直接在Activity类中调用
2.1.2 方式二
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2.1.3 方式三
LayoutInflater inflater = LayoutInflater.from(context); //说明:context是当前上下文
可以看出,方式三就是方式二的简单写法,只是Android做了一下封装。
2.2 使用LayoutInflater的inflate()方法加载布局文件
inflate()方法有如下几种重载的方法:
方法1:public View inflate(XmlPullParser parser, ViewGroup root) 方法2:public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法3:public View inflate(int resource, ViewGroup root) 方法4:public View inflate(int resource, ViewGroup root, boolean attachToRoot) //说明:方法1和方法2是通过XmlPullParser作为数据源创建View对象;方法3和方法4是通过resource目录下的布局文件 作为数据来源创建View对象 //说明:参数resrource表示就是要加载的布局的id 参数root表示给该布局的外部再嵌套一层父布局,如果不需要,则传入null
3.实例
3.1 代码和布局
1)activity_main.xml中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> </LinearLayout>
2)自定义一个包含按钮的布局:
<Button xmlns:android:"http://shcemas.android.com/apk/res/android" android:layout_width="wra_content" android:layout_height="wrap_content" android:text="Button"> </Button>
3)MainActivity中:
public class MainActivity extends Activity{ @Override public void onCreate(Bundled savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout mainLayout = findViewById(R.id.main_layout); LayoutInflater inflater = LayoutInflater.from(this); View buttonLayout = inflater.inflater(R.layout.button_layout,null); mainLayout.addView(buttonLayout); } }
3.2 效果
如下图所示:按钮被添加到了页面中: