1.LayoutInflater与findViewById区别
1、LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;
对于一个没有被载入或者想要动态载入的界面,都需要使用 LayoutInflater.inflate()来载入.
2、findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等);
对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
2.获得 LayoutInflater 实例的三种方式
LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
LayoutInflater inflater = LayoutInflater.from(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3.inflate
从指定的xml资源中填充新的视图层次结构
inflate方法一:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
inflate方法二:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
if (view != null) {
return view;
}
XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
4.参数详解:
resource:
要添加的布局资源文件
root:
可选视图作为生成的层次结构的父级
null和有值的区别 null时第一个参数中最外层的布局大小无效,有值的时候最外层的布局大小有效
attachToroot:
是否将层次结构的布局文件添加到父视图
if (attachToRoot) {
root.addView(view, params);
} else {
view.setLayoutParams(params);
}
若attachToRoot为true且root不为null,则调用root.addView()方法
4.attachToRoot什么时候为true:
Adapter不能将attachToRoot参数设置为true;
在为fragment创建布局时,如果为true,那么这个布局文件就会被添加到父activity中盛放fragment的布局中。