LayoutInflater.inflate()的作用就是将一个xml定义的布局文件实例化为view控件对象;
与findViewById区别:
LayoutInflater.inflate是加载一个布局文件;
findViewById则是从布局文件中查找一个控件;
一.获取LayoutInflater对象有三种方法
LayoutInflater inflater=LayoutInflater.from(context);
LayoutInflater inflater=getLayoutInflater();在Activity中可以使用,实际上是View子类下window的一个函数
LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
二:inflate 参数
public View inflate(int resource, ViewGroup root, boolean attachToRoot) :
reSource:View的layout的ID
root:需要附加到resource资源文件的根控件,inflate()会返回一个View对象,如果第三个参数attachToRoot为true,就将这个root作为根对象返回,否则仅仅将这个root对象的LayoutParams属性附加到resource对象的根布局对象上,也就是布局文件resource的最外层的View上。如果root为null则会忽略view根对象的LayoutParams属性(注意)。
attachToRoot:是否将root附加到布局文件的根视图上
例子:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.fragment, root,false);
或者:
v = inflater.inflate(R.layout.fragment, null);
常见问题:
有时候我们在Adapter加载自定义的view布局文件,布局文件中设置了android:layout_height="100dip",但是运行程序后发现一点作用都没有,相似的还有layout_width等以android:layout_开头的属性设置都没有作用;
因为Adapter里有一个方法是getView,这个返回的VIew是一个从XML布局里加载的,一般如下:
View v = inflater.inflate(R.layout.fragment, null);
问题恰恰出在我们的LayoutInflater.from(mContext).inflate(R.layout.main, null);这句代码上,在使用inflate的时候,如果第二个参数(View root)为null,那么将不会加载你的布局文件里的最顶层的那个布局节点的布局相关配置(就是以android:layout_开头的属性)..我们可以看下该方法的实现来说明一下,通过查找源代码,inflate的实现都在这个public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法里定义。。其中一段:
if (root != null) { if (DEBUG) { System.out.println("Creating params from root: " + root); } // Create layout params that match root, if supplied params = root.generateLayoutParams(attrs); if (!attachToRoot) { // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp.setLayoutParams(params); } }
代码中可以发现:当root为null的时候是不会执行params = root.generateLayoutParams(attrs);这段代码的,这段代码就是把xml里的布局配置转为LayoutParams,换句说就是加载我们配置的布局属性,以供布局类(FrameLayout等)在onLayout的时候控制View的大小、位置、对齐等等。。以FrameLayout为例,看下它的generateLayoutParams(attrs)方法。
解决办法:
使用LayoutInflate的inflate方法的时候一定要保证root参数不能为null,其实这个root就是父View的意思,就是说你把xml转换为一个VIew的时候,该VIew的Parent是root,如果你不想把该View添加到该root里,那么让第三个参数 attachToRoot为false,如果要添加则为true.