View Binding — Overview

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

Open the build.gradle file for your project

allprojects {
repositories {
google()
jcenter()
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "androidx.lifecycle:lifecycle-viewmodel:2.1.0"

}

Enable View Binding OR Data Binding

dataBinding {
enabled = true
}

Before starting the project let see the advantage of the View Binding

  1. Avoid Null Pointer Exception
  2. Type Safe
  3. Event Handling (Method references and Listener bindings )
  4. 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.fname}, if user is null, user.fname is assigned its default value of null.

Type Safe

The fields in each binding class have types matching the views they reference in the XML file.

Event Handling

Method references

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 View 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

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.

--

--

Mobile Application Developer | Flutter Developer | Project Manager | Team Leader | Scrum Certified | PMI APC Appeard | Writing (starting soon)

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suraj Vishwakarma

Suraj Vishwakarma

17 Followers

Mobile Application Developer | Flutter Developer | Project Manager | Team Leader | Scrum Certified | PMI APC Appeard | Writing (starting soon)