android - 在 Fragments 中使用 View 绑定(bind)在哪里更好? (onCreateView 与 onViewCreated)

标签 android android-fragments android-viewbinding

我看到了一些示例,其中使用 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 = nullonDestroyView以防止泄漏。

关于android - 在 Fragments 中使用 View 绑定(bind)在哪里更好? (onCreateView 与 onViewCreated),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68190680/

相关文章:

java - 未找到 fragment 类

android - 无法收听向上插入符号的点击

android - 查看绑定(bind)不适用于 "Include": incompatible types: ProgressBarLayoutBinding cannot be converted to ViewDataBinding

android - fragment 最佳实践 - Android

android - 使用 View 绑定(bind)访问另一个 Activity 的 UI 元素

android - ViewBinding vs Kotlin Android Extensions 与合成 View

android - 如何设置动态 channel 名称

Android LogCat sqlite语法错误含义

java - Firebase - 查询嵌套键?

android - WebView - 登录成功后返回 Facebook 评论