View Binding in Android
Use view binding to replace findViewById()
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. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.
Instead of calling findViewById()
for each View
in your app, you'll create and initialize a binding object once.Now when you need a reference to a View
in your app, you can get it from the binding
object instead of calling findViewById()
.
The binding
object automatically defines references for every View
in your app that has an ID. Using view binding is so much more concise that often you won't even need to create a variable to hold the reference for a View
, just use it directly from the binding object.
🤔 Now you might be thinking of how to setup the instructions for View binding
Nothing drudgery task to do just set the viewBinding
build option to true
in the module-level build.gradle
file, as shown in the following example:
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, given a layout file called result_profile.xml
:
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.
👉Differences from findViewById
View binding has important advantages over using findViewById
:
- Null safety: Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID. Additionally, when a view is only present in some configurations of a layout, the field containing its reference in the binding class is marked with
@Nullable
. - Type safety: The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception.
These differences mean that incompatibilities between your layout and your code will result in your build failing at compile time rather than at runtime.
Hope you got a basic idea of View Binding in Android and its advantages over findViewById()