在很多地方看见过LayoutInflater的不同用法,现将几种常用的方法总结一下。
LayoutInflater 是一个抽象类,其作用类似于findViewById(),
不同的是:LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;
而findViewById()是找xml布局文件下的具体的控件(如Button、TextView等)。
实际使用中,
1、对于一个没有被载入或者想要动态载入的界面,需要使用LayoutInflater.inflate()来载入。
2、对于一个已经载入的界面,可以使用()this.findViewById(R.id.XXX)方法来获得其中的界面元素。
获得LayoutInflater实例的三种方式;
1、LayoutInflater inflater = getLayoutInflater();
2、LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3、LayoutInflater inflater = LayoutInflater.from(context);
本质上来说,这三种方式是一样的,如看源码我们知道,
getLayoutInflater()其实是调用 LayoutInflater.from(context),源码:
public PhoneWindow(Context context)
{
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
LayoutInflater.from(context)
是调用context.getSystemService()。源码:
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;
}
本质上都是调用(LayoutInflater)context.getSystemService()。
如(LayoutInflater)context.getSystemService()的使用:
LayoutInflater inflater =(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popupwindow,(ViewGroup)findViewById(R.id.test));
这里指定了inflate()方法的第二个参数为
(ViewGroup)findViewById(R.id.test)
实际上,可以设置的null。
Tips: inflate() 方法与 findViewById() 方法不同,
inflater() 是用来查找 res/layout下的xml布局文件,并且实例化。
而findViewById() 是查找具体xml布局文件中的实际控件(如:Button、TextView 等)。