hi-dhl/Binding

Fragment onCreateView中使用的方式,inflate缺少parent参数

start141 opened this issue · 6 comments

Fragment onCreateView中使用的方式,inflate缺少parent参数

你好,我想咨询一下,如果不添加这个 parent 这个参数,在什么场景中,会出现什么问题,因为我使用 Navigation 的场景不是很多

你好,我想咨询一下,如果不添加这个 parent 这个参数,在什么场景中,会出现什么问题,因为我使用 Navigation 的场景不是很多

parent传null会使根部局的layout属性失效。

你好,我想咨询一下,如果不添加这个 parent 这个参数,在什么场景中,会出现什么问题,因为我使用 Navigation 的场景不是很多

parent传null会使根部局的layout属性失效。

我先说一下我的理解。

layout属性我理解为是 layout_width 、layout_height

根部局: 我的理解是 layout 布局文件的根 view ,即 rootView

根据源码我的理解是这样的:

parent 传 null 不会使用 parent 的布局参数,但是会使用根部局的 layout 属性, 也就是说 layout 布局文件的根 view 布局参数是生效的 ,而一般我们很少会使用 parent 的布局参数

源码如下所示:

 public static FragmentNav1Binding inflate(@NonNull LayoutInflater inflater,
     @Nullable ViewGroup parent, boolean attachToParent) {
   View root = inflater.inflate(R.layout.fragment_nav_1, parent, false);
   if (attachToParent) {
     parent.addView(root);
   }
   return bind(root);
 }

attachToParent 为 true 会将 inflater.inflate 返回的 view 添加进 parent 中

inflater.inflate 源码大概意思如下所示:

  • 当 attachToRoot == true 且 root != null 时,新解析出来的 View 会被 add 到 root 中去,然后将 root 作为结果返回
  • 当 attachToRoot == false 且 root != null 时,新解析的 View 会直接作为结果返回,而且 root 会为新解析的 View 生成 LayoutParams 并设置到该 View 中去
  • 当 attachToRoot == false 且 root == null 时,新解析的 View 会直接作为结果返回

我在实践中是生效的,能举一个不生效的例子吗,我研究一下,做一下特殊情况下的适配,非常感谢

root为null的话,被inflate的layout的根布局的layout_width、layout_height不生效,会导致某些布局宽高不符合预期。

我随便找的两篇文章,你可以参考验证一下:
1、http://hoyouly.fun/2020/04/07/inflate/ (扫盲系列 - layoutInflater中 inflate() 参数总结)
2、https://blog.csdn.net/u012702547/article/details/52628453 (三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别)

非常感谢你的提交,这个问题在 1.0.9 上修复了,之前旧的 方式一 依然保留,但是不建议在使用了