public View inflate (int resource, ViewGroup root, boolean attachToRoot) 的第三个参数是做什么的?

what does 3rd parameter of public View inflate (int resource, ViewGroup root, boolean attachToRoot) do?

According to android.developer.com

root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)

attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

LayoutParams 的这个子类是什么?函数参数中提到的resource的layout参数怎么办?

我尝试了 true 和 false 的组合作为第三个参数,唯一的区别似乎是 resource 是否作为子项附加。 xml 文件中提到的 resource 的布局参数在这两种情况下都有效。

如果设置为 true,那么当您的布局(资源)膨胀时,它将作为子级自动添加到在第二个参数中指定的 ViewGroup 的视图层次结构中。例如,如果根参数是 LinearLayout,那么您的膨胀视图将自动添加为该视图的子视图。

如果它设置为 false,那么您的布局将被放大但不会附加到任何其他布局(因此它不会被绘制、接收触摸事件等)。

public View inflate (int resource, ViewGroup root, boolean attachToRoot)到底是什么意思?

它指向您要扩充的布局资源。第二个参数是您正在扩展要附加到的资源的层次结构的根视图。当存在第三个参数时,它控制膨胀视图是否在 inflation.

之后附加到提供的根。

最后两个参数可能会引起一些混淆。使用此方法的两个参数版本,LayoutInflater 将自动尝试将膨胀视图附加到提供的根。但是,该框架有一个检查,如果您为根传递 null,它会绕过此尝试以避免应用程序崩溃。

在大多数情况下,如果允许 LayoutInflater 自动将膨胀视图附加到根,它将在稍后抛出异常。

如果我们不应该附加到这个 ViewGroup,为什么要给它?

事实证明,父视图是 inflation 过程中非常重要的一部分,因为它是评估 XML 的根元素中声明的 LayoutParams 所必需的。在这里不传递任何内容类似于告诉框架“抱歉,因为我不知道这个视图实际上将附加到哪个父级”。

reference