The Data Binding Library generates binding classes you can use to access the layout's variables and views. This documentation shows how to create and customize generated binding classes.
The generated binding class links the layout variables with the views within the
layout. You can customize the name and package of
the binding. All generated binding classes inherit from the
ViewDataBinding class.
A binding class is generated for each layout file. By default, the name of the
class is the name of the layout file converted to Pascal case with the Binding
suffix added to it. So, for example, if the layout filename is
activity_main.xml, the corresponding generated class is ActivityMainBinding.
This class holds all the bindings from the layout properties to the layout's
views and knows how to assign values for the binding expressions.
Create a binding object
The binding object is created immediately after inflating the layout to make
sure the view hierarchy isn't modified before it binds to the views with
expressions within the layout. The most common method to bind the object to a
layout is to use the static methods on the binding class. You can inflate the
view hierarchy and bind the object to it by using the inflate() method of the
binding class, as shown in the following example:
Kotlin
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: MyLayoutBinding = MyLayoutBinding.inflate(layoutInflater) setContentView(binding.root) }
Java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyLayoutBinding binding = MyLayoutBinding.inflate(getLayoutInflater()); setContentView(binding.root); }
There is an alternate version of the inflate() method that takes a
ViewGroup object in addition to the
LayoutInflater object , as
shown in the following example:
Kotlin
val binding: MyLayoutBinding = MyLayoutBinding.inflate(getLayoutInflater(), viewGroup, false)
Java
MyLayoutBinding binding = MyLayoutBinding.inflate(getLayoutInflater(), viewGroup