在 Fragment 中哪里使用视图绑定更好?(onCreateView 与 onViewCreated)

MrA*_*tyD 4 android android-fragments android-viewbinding

我看到一些示例,其中使用 inflate() 在 onCreateView() 中定义和使用绑定,并在 onViewCreated() 中使用 bind() 定义和使用绑定。

有什么不同?那么我们的视图(RecyclerView、TextView等)在哪里操作比较好呢?

谷歌文档显示了这样的示例:

override fun onCreateView(
   inflater: LayoutInflater,
   container: ViewGroup?,
   savedInstanceState: Bundle?
): View? {
   _binding = ResultProfileBinding.inflate(inflater, container, false)
   val view = binding.root
   return view
}
Run Code Online (Sandbox Code Playgroud)

但在一些文章中我们也可以看到这样的内容:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    _binding = ResultProfileBinding.bind(view)
}
Run Code Online (Sandbox Code Playgroud)

小智 5

使用初始化绑定是一种很好的做法,onCreateview因为它会在视图创建的同时膨胀布局,然后在内部使用 thisonViewCreated和其他函数。

您还需要做好防止泄漏的_binding = null工作。onDestroyView