android inflater 参数,LayoutInflater.inflate()方法两个参数和三个参数
转载请标明出处:https://www.cnblogs.com/tangzh/p/7074853.html很多人都用过layoutinflater(布局填充器)对于我来说通常使用下面两种:layoutinflater.from(context).inflate(r.layout.recycle_foot_item,null);layoutinflater.from(context).inflate
转载请标明出处:https://www.cnblogs.com/tangzh/p/7074853.html
很多人都用过layoutinflater(布局填充器)
对于我来说通常使用下面两种:
layoutinflater.from(context).inflate(r.layout.recycle_foot_item,null);
layoutinflater.from(context).inflate(r.layout.recycle_foot_item,parent,false);
那么两个参数与三个参数究竟有什么区别呢?
我们进去源码看一下两个参数时的代码:
public view inflate(@layoutres int resource, @nullable viewgroup root) {
return inflate(resource, root, root != null);
}
可以看出来使用两个参数时,它的内部也是调用了3个参数的方法。
如果我们使用layoutinflater.from(context).inflate(r.layout.recycle_foot_item,null);
则实际上是调用了layoutinflater.from(context).inflate(r.layout.recycle_foot_item,null,null!=null);
等同于:layoutinflater.from(context).inflate(r.layout.recycle_foot_item,null,false);
如果我们使用layoutinflater.from(context).inflate(r.layout.recycle_foot_item,parent);
则实际上是调用了layoutinflater.from(context).inflate(r.layout.recycle_foot_item,parent,parent!=null);
等同于:layoutinflater.from(context).inflate(r.layout.recycle_foot_item,parent,true);
我们再来看看三个参数的方法的源码:
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) + ")");
}
final xmlresourceparser parser = res.getlayout(resource);
try {
return inflate(parser, root, attachtoroot);
} finally {
parser.close();
}
}
在里面调用了
inflate(parser, root, attachtoroot);方法,在源码中可以看到,inflate(parser, root, 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);
}
}
.
.
.
// we are supposed to attach all the views we found (int temp)
// to root. do that now.
if (root != null && attachtoroot) {
root.addview(temp, params);
}
从上面可以看出:
如果第二个和第三个参数均不为空的话,即root不为null,而attachtoroot为true的话那么我们执行完layoutinflater.from(context).inflate(r.layout.recycle_foot_item,parent,true);之后,r.layout.recycle_foot_item就已经被添加进去parent中了,我们不能再次调用parent.add(view view)这个方法,否则会抛出异常。
那么root不为null,attachtoroot为false是代表什么呢?我们可以肯定的说attachtoroot为false,那么我们不将第一个参数的view添加到root中,那么root有什么作用?其实root决定了我们的设置给第一个参数view的布局的根节点的layout_width和layout_height属性是否有效。我们在开发的过程中给控件所指定的layout_width和layout_height到底是什么意思?该属性的表示一个控件在容器中的大小,就是说这个控件必须在容器中,这个属性才有意义,否则无意义。所以如果我们不给第一个参数的view指定一个父布局,那么该view的根节点的宽高属性就失效了。
如果我想让第一个参数view的根节点有效,又不想让其处于某一个容器中,那我就可以设置root不为null,而attachtoroot为false。这样,指定root的目的也就很明确了,即root会协助第一个参数view的根节点生成布局参数,只有这一个作用。
但是这个时候我们要手动地把view添加进来。
更多推荐
所有评论(0)