如何在DialogFragment中正确使用AndroidView Binding?

How to correctly use Android View Binding in DialogFragment?

在 DialogFragment() 中使用 Android 视图绑定的正确方法是什么?

官方文档只提到Activity和Fragment: https://developer.android.com/topic/libraries/view-binding

改用inflate(LayoutInflater.from(context))。并使用 binding.root 设置构建器视图。

此外,正如 Google 所建议的那样,最佳做法是在使用片段时将 binding 实例在 onDestroyView() 处设置为 null: 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
    } 
}