我看到了一些示例,其中使用 inflate() 在 onCreateView() 中定义和使用绑定(bind),在使用 bind() 的 onViewCreated() 中定义和使用绑定(bind)。
有什么不同?使用我们的 View (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)
}
最佳答案
最好在 onCreateview
中使用初始化绑定(bind)。因为它会在 View 创建的同一时刻膨胀布局,然后在 onViewCreated
内部使用它和其他功能。
您还需要制作 _binding = null
在 onDestroyView
以防止泄漏。
关于android - 在 Fragments 中使用 View 绑定(bind)在哪里更好? (onCreateView 与 onViewCreated),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68190680/