如何在DialogFragment中正确使用Android View绑定? [英] How to correctly use Android View Binding in DialogFragment?
问题描述
在DialogFragment()中使用Android视图绑定的正确方法是什么?
What is correct way of using Android View Binding in DialogFragment()?
官方文档仅提及活动和片段: https://developer.android.com/topic/libraries/view-binding
Official documentation mentions only Activity and Fragment: https://developer.android.com/topic/libraries/view-binding
推荐答案
请改用 inflate(LayoutInflater.from(context))
.并使用 binding.root
设置构建器视图.
Use inflate(LayoutInflater.from(context))
instead. And use binding.root
to set the builder view.
此外,正如Google所建议的那样,最佳做法是在使用片段时,在 onDestroyView()
上将 binding
实例设置为null: https://developer.android.com/topic/libraries/view-binding#fragments
Also, as Google suggests, it's best practice to set the binding
instance to null at onDestroyView()
when using fragments:
https://developer.android.com/topic/libraries/view-binding#fragments
示例:
class ExampleDialog : DialogFragment() {
private var _binding: DialogExampleBinding? = null
// This property is only valid between onCreateDialog and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = DialogExampleBinding.inflate(LayoutInflater.from(context))
return AlertDialog.Builder(requireActivity())
.setView(binding.root)
.create()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
这篇关于如何在DialogFragment中正确使用Android View绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!