In most cases, view binding replaces findViewById
View binding is a feature that makes it easier to 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. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.
Setup
View binding is enabled on a module-by-module basis. To enable view binding in a
module, set the viewBinding build option to true in the module-level
build.gradle file, as shown in the following example:
android {
...
buildFeatures {
viewBinding = true
}
}
If you want a layout file to be ignored while generating binding classes, add
the tools:viewBindingIgnore="true" attribute to the root view of that layout
file: <LinearLayout
...
tools:viewBindingIgnore="true" >
...
</LinearLayout>
Usage
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.
For example, consider a layout file called result_profile.xml that contains
the following:
<LinearLayout ... >
<TextView android:id="@+id/name" />
<ImageView android:cropToPadding="true" />
<Button android:id="@+id/button"
android:background="@drawable/rounded_button" />
</LinearLayout>
The generated binding class is called ResultProfileBinding. This class has two
fields: a TextView called name and a Button called button. The
ImageView in the layout has no ID, so there is no reference to it in the
binding class.
Every binding class also includes a getRoot() method, providing a direct
reference for the root view of the corresponding layout file. In this example,
the getRoot() method in the ResultProfileBinding class returns the
LinearLayout root view.
The following sections demonstrate the use of generated binding classes in activities and fragments.
Comments
Post a Comment