转载请标明出处:https://www.cnblogs.com/tangZH/p/7074853.html
更多精美文章:http://77blogs.com/?p=489
很多人都用过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添加进来。