第一种方法:膨胀子视图的两种方法有什么区别吗?
LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, parent, true);
第二种方法:
LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, null, false);
parent.addView(child);
有什么区别?
第一种方法:膨胀子视图的两种方法有什么区别吗?
LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, parent, true);
第二种方法:
LinearLayout parent = ...;
View child = LayoutInflator.inflate(context, null, false);
parent.addView(child);
有什么区别?
如果你检查充气方法的来源,你会发现:
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);
}
所以在你的例子是没有区别的。
会有在这种情况下
View child = LayoutInflator.inflate(context, parent, false);
孩子将有相同的LayoutParams父有差别,但它不会被附着所以这将是刚刚独立的视图。
不同之处在于你的第二个参数,它主要告诉Android哪个视图是你正在膨胀的视图的父视图。
在第一种情况下,视图将被膨胀到ViewGroup中,该ViewGroup是“父”实例。在第二种情况下,新创建的视图没有父项,并且将按原样膨胀。
据Android开发者文档:
View child = LayoutInflator.inflate(context, parent, true);
会对孩子添加到父,
View child = LayoutInflator.inflate(context, null, false);
不会。
你可以检查出的参考:android.view.ViewGroup.inflate
是 如果真 - :是否充气层次结构应附着在根参数?
if False - 如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。
这个参数一般用于我们不想使用Adapter类在Listview中添加行的情况 我们希望通过视图或布局来制作他们具有子视图的行,在这种情况下我们使用它。
假设您已拨打context
资源ID进行膨胀,这非常令人困惑。有以下区别:
布局资源顶层的布局参数的使用,取决于parent
布局参数。在第二种情况下,这些布局参数将不会被应用;
从source code如下:
471 if (root != null) {
472 if (DEBUG) {
473 System.out.println("Creating params from root: " +
474 root);
475 }
476 // Create layout params that match root, if supplied
477 params = root.generateLayoutParams(attrs);
478 if (!attachToRoot) {
479 // Set the layout params for temp if we are not
480 // attaching. (If we are, we use addView, below)
481 temp.setLayoutParams(params);
482 }
483 }
484
485 if (DEBUG) {
486 System.out.println("-----> start inflating children");
487 }
488 // Inflate all children under temp
489 rInflate(parser, temp, attrs, true);
490 if (DEBUG) {
491 System.out.println("-----> done inflating children");
492 }
493
494 // We are supposed to attach all the views we found (int temp)
495 // to root. Do that now.
496 if (root != null && attachToRoot) {
497 root.addView(temp, params);
498 }
499
500 // Decide whether to return the root that was passed in or the
501 // top view found in xml.
502 if (root == null || !attachToRoot) {
503 result = temp;
504 }
从线471〜482,将设置儿童的布局PARAMS查看新创建PARAMS其匹配父视图。
从第496行到第498行,父级添加子视图和布局参数。
所以区别在于是否设置了子视图的布局参数