image.png
开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。
不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化.
而findViewById()是找xml布局文件下的具体widget控件(如 Button、TextView等)。
使用场景:
LayoutInflater.inflate()
来载入。Activiyt.findViewById()
方法来获得其中的界面元素。public abstract class LayoutInflater extends Object
获得 LayoutInflater 实例的三种方式:
LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
LayoutInflater localinflater =(LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context);
getLayoutInflater
方法是Activity方法,调用 PhoneWindow 的getLayoutInflater()方法,看一下该源代码:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
内部其实调用了LayoutInflater.from(context)
方法。
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;
}
内部其实调用的是getSystemService
方法。
public View inflate (int resource, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
使用代码:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));
EditText editText = (EditText)view.findViewById(R.id.content);