转载地址:https://blog.csdn.net/u012702547/article/details/52628453 (讲的非常好)
我们一般加入一个View进来的方式是哪种?
...
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.linearlayout, ll,false);
ll.addView(view);//把视图加载进来
...
是不是像上面那样把一个View加载进来
常见疑惑1:我把false改为true会怎样?
如果你把false改为true,ll.addView(view);这句代码就要删除了否则会报如下错。
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
删除后正确的代码如下(最后显示的效果同上):
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.linearlayout, ll,true);
- 值为true:
将resource指定的布局添加到root中,且添加的过程中resource所指定的的布局的根节点的各个属性都是有效的,你在resource里面设置的layout_width=100dp或者是layout_height=100dp在根视图里面显示是有效果的。 - 值为false:
不将resource添加到root中(此时的resource不处于任何容器中,但是我们可以手动addView进来,让它处于某一个容器里面,root会协助resource的根节点生成布局参数),你在resource里面设置的layout_width=100dp或者layout_height=100dp显示也是有效果的。 - 总结:
设置为true和false,只是影响了resource是否添加到了根视图里面。
常见疑惑2:我将root设置为null会怎样?
不将resource添加root中,我第三个参数是true还是false都没有任何意义了。里面设置的宽高都不会有任何的价值。