LayoutInflater中的inflate方法详解(转载整理)

我们最常用的便是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(parserrootattachToRoot);

3中调用了:inflate(parserrootroot != 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

2、http://blog.csdn.net/xyz_fly/article/details/21301303

3、http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/view/LayoutInflater.java?av=f

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值