36

What is correct way of using Android View Binding in DialogFragment()?

Official documentation mentions only Activity and Fragment: https://developer.android.com/topic/libraries/view-binding

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
Valeriya
  • 1,067
  • 2
  • 16
  • 31

1 Answers1

56

Use inflate(LayoutInflater.from(context)) instead. And use binding.root to set the builder view.

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

Example:

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
    } 
}
hamrosvet
  • 1,178
  • 12
  • 15