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

标签 android view layoutparams

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 的布局参数会发生什么变化?

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

最佳答案

public View inflate (int resource, ViewGroup root, boolean attachToRoot) 的真正含义是什么?

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

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

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

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

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

reference

关于android - public View inflate (int resource, ViewGroup root, boolean attachToRoot) 的第三个参数是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35402517/

相关文章:

android - 如何在使用 android 在 Instagram 上发布时添加带有图像的标题(像位图这样的对象)

java - Android 中 Activity 的 +1 按钮始终呈灰色

Java 类泛型导致类扩展该类型?

android - 确定 Android 屏幕尺寸并相应地设置 View 的尺寸

Android VideoView 调整大小不会调整视频大小

android - 以编程方式在 RecyclerView 上设置边距

android - 手势检测器不工作

android - OnItemClick 监听器和单击的 View 项的可见性

ruby-on-rails - 如何在 Rails 的 application.html.erb 中显示不同的 header ?

android - 图实现Android