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
How to Implement View Binding Inside Dialog in Android? In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.
Use view binding in fragments To set up an instance of the binding class for use with a fragment, perform the following steps in the fragment's onCreateView () method: Call the static inflate () method included in the generated binding class. This creates an instance of the binding class for the fragment to use.
If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class contains references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word "Binding" to the end.
You can create a DialogFragment and display a dialog by overriding onCreateView () , either giving it a layoutId as you would with a typical fragment or using the DialogFragment constructor. The View returned by onCreateView () is automatically added to the dialog.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With