获取填充对象
1
LayoutInflater inflater=LayoutInflater.from(context);
2
LayoutInflater inflater= getLayoutInflater();
3
LayoutInflater inflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
这三种获取填充对象的方式如出一辙,第二种是调用activity的getLayoutInflater(),实际上是调用PhoneWindow的getLayoutInflater()
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
第三种实际上就是系统对第一种进行的封装
@Override
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return mInflater;
}
return getBaseContext().getSystemService(name);
}
填充方式
1
View view = LayoutInflater.from(context).inflate(int resource, ViewGroup root);
第一个参数是布局文件id,第二个参数root是当前填充布局的父布局,如果没有父布局就填null。这样可以把view添加到准备好的布局中,如果父布局root不为null,默认attachToRoot为true,为true的目的是填充布局会自动添加到父布局中,不用手动addView。
2
除了有两个个参数的inflate(resourceId, root);,还发现有三个参数的填充方式。
LayoutInflater.from(context).inflate(int resource, ViewGroup root, boolean attachToRoot);
如果设置root为null,attachToRoot将失去作用,无论设置的是false还是true。
如果不为空的话,attachToRoot为false,填充布局不会被直接add进布局,需要调用父布局的addView 方法添加进去,这时候父布局的属性自动生效。;
LayoutInflater.from(context).inflate(int resource, ViewGroup root, false);
此时如果attachToRoot为true,再次addView的话,会造成重复添加。
getView方法中attachToRoot必须为false,getView会不断的自动添加和销毁View,如果为true,会造成多次添加异常。
activity中setContentView没有设置root,我们会以为root为null,最外层的布局无论设置什么属性都不起作用。但是为什么我们可以设置最外层的属性并且生效,因为系统在我们的布局文件外面加了一层FrameLayout。