How to correctly use Android View Binding in DialogFragment?

11,021

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
    } 
}
Share:
11,021

Related videos on Youtube

Valeriya
Author by

Valeriya

Android developer since 2016, Uzbekistan. Bachelor of Science in Business Information Systems, Westminster International University in Tashkent. A girl in love with programming :)

Updated on September 15, 2022

Comments

  • Valeriya
    Valeriya over 1 year

    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

  • Mehmed
    Mehmed over 3 years
    This is recommended to prevent crashes but what happens if binding is used after it is set to null? I think it will crash, which means private val binding get() = _binding!! makes no sense at all. Am I missing something?
  • Nino DELCEY
    Nino DELCEY almost 3 years
    You shouldn't use the view once it reaches the onDestroyView life cycle.
  • Nino DELCEY
    Nino DELCEY almost 3 years
    Also, it is a better pratice to use your binding as a local variable. No need to override onDestroyView in this case ! :)