Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use Android View Binding in DialogFragment?

Tags:

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

like image 883
Valeriya Avatar asked Apr 14 '20 10:04

Valeriya


People also ask

What is view binding inside dialog in Android?

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.

How do I bind a view to a fragment?

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.

How do I bind a view to a module?

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.

How do I display a dialog in a dialogfragment?

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.


1 Answers

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     }  } 
like image 194
hamrosvet Avatar answered Sep 16 '22 12:09

hamrosvet