android - 在 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)
}
解决方案
使用初始化绑定是一个很好的做法,onCreateview
因为它会在视图创建的同时膨胀布局,然后在内部onViewCreated
和其他函数中使用它。
此外,您需要制作_binding = null
以onDestroyView
防止泄漏。
推荐阅读
- html - 包含具有边距和填充的正确子级
- php - 如何使用或不使用php将unicode文本数据解码回excel文件?
- php - Laravel 5.8 - 如何保护存储目录免受路由?
- c# - 给定一个将方法作为输入的方法,获取其类和方法名
- android - 微调器单击 EditText
- ajax - 使用 ajax 从 youtube api 加载大量视频
- sql - LEFT 外连接返回返回重复的行,即使添加了不同的
- twig - 转储(项目)在 Twig 模板 drupal 中不起作用
- python - 将csv转换为熊猫
- javascript - 如何为此javascript代码创建自动循环?