我们最常用的便是LayoutInflater的inflate方法,这个方法重载了四种调用方式,分别为:
1.public View inflate(int resource, ViewGroup root)
2.public View inflate(int resource, ViewGroup root, boolean attachToRoot)
3.public View inflate(XmlPullParser parser, ViewGroup root)
4.public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
其中:
1.resource 布局的资源id
2.root 填充的根视图
3.attachToRoot 是否将载入的视图绑定到根视图中
4.parser Xml解析布局文件,生成View对象。
然后1中调用了:inflate(resource, root, root != null);
2中调用了:inflate(parser, root, attachToRoot);
3中调用了:inflate(parser, root, root != null);
因此虽然重载了四个方法,但是这四种方法最终调用的,还是第四种方式。第四种方式也很好理解,内部实现原理就是利用Pull解析器,对Xml文件进行解析,然后返回View对象。
在实现ListView的Adapter的时候我们经常可能会这样:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, null);
}
return convertView;
}
但是我们,在使用的时候可能就会发现一个问题,就是当我们在设置了我们的Item的高度,或者其他属性的时候没有效果,还是warp_content的效果。这就是我们没有使用正确的inflate方法。
这里我们有个例子我们可以看一看(具体的代码就不拿出来了,是个简单的例子):
第一张实现方式和效果如下:
inflate(R.layout.item_row, null);
第二张实现方式和效果如下:
inflater.inflate(R.layout.item_list, parent,false);
其中在布局Item的时候我们有设置高度为60dp,但是我们的第一张图显然是没有体现出来的,根本没有间距。第二张图,体现了出来。从这里我们可以看出使用第一种方式是没有办法实现的。具体的原因我们可以从其中最关键的一段代码中看见:
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&&!attachToRoot的时候我们才会去设置我们的布局的参数,因此我们的第一个方法他是没有传入这两个参数的,因此其实在实现的时候是没有设置我们的布局参数的。因此我们的设置是没有效果的。
通过这个例子,我想我们大概就应该就明白了inflate方法该如何使用了。
参考:
1、http://www.2cto.com/kf/201407/313054.html