View Binding — Overview
In this section we will be looking the Overview of View Binding. In case you have already complete the Part I you can directly jump to Layout Expression
Android Architecture Components
Android architecture components are a collection of libraries that help you design robust, testable, and maintainable apps.
Components Adding to your Project
build.gradle file for your project
build.gradle file for your app or module
Enable View Binding OR Data Binding
enabled = true
Before starting the project let see the advantage of the View Binding
- Avoid Null Pointer Exception
- Type Safe
- Event Handling (Method references and Listener bindings )
- Lesser the code in activity
Avoid Null Pointer Exception
Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid views ID. For Exampel the expression
user is null,
user.fname is assigned its default value of
The fields in each binding class have types matching the views they reference in the XML file.
Events can be bound to handler methods directly, similar to the way
android:onClick can be assigned to a method in an activity. One major advantage compared to the
onClick attribute is that the expression is processed at compile time, so if the method doesn't exist or its signature is incorrect, you receive a compile time error.
Listener bindings are binding expressions that run when an event happens.
Major Difference between Method references and Listener bindings
Method references and listener bindings is that the actual listener implementation is created when the data is bound, not when the event is triggered. If you prefer to evaluate the expression when the event happens, you should use listener binding.
We will see the implementation of the view binding in Layout Expression.