首页 > 解决方案 > 在 Fragments 中使用视图绑定在哪里更好?(onCreateView 与 onViewCreated)

问题描述

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

有什么不同?使用我们的视图(RecyclerView、TextView 等)在哪里操作更好?

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

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

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

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

    _binding = ResultProfileBinding.bind(view)
}

标签: androidandroid-fragmentsandroid-viewbinding

解决方案


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

此外,您需要制作_binding = nullonDestroyView防止泄漏。


推荐阅读