How to Use data Binding in Android

How to Use Data Binding in Android

What is Data Binding?

Databinding is a part of android-architecture components in an android jetpack. It is a support library and It is used to bind UI components in the layout to data resources in your app. In another word, we can say that Databinding allows you to write expressions that connect variables to the views in the layout.

Data Binding Library automatically creates the classes required to bind the views in the layout with your data objects. Databinding is useful for reducing boilerplate code from the source code that is usually written to sync the UI when new data is available. When the data changes its value, the elements that are bound to the data reflect changes automatically.

Which types of devices can use data binding?

Devices running Android 4.0 (API level 14) or higher can be used data binding.

How to use data binding in an android project?

Step 1:

In build.gradle of the app module

Step 2:

In creating a class for binding view

For Callback:

Step 3:

Add the binding class in XML layout.

fileName activity_main.xml


After that a class is generated automatically in the 
build/generated folder inside the app module. The class name will be on the name of xml file name i.e If data binding is used in activity_main.xml then ActivityMainBinding will be a generated data binding class. In this class, the Method name is generated from the variable name in the file.

Step 4:

Binding Recyclerview with adapter

Step 1:

Add the following dependency in build.gradle

FileName activity_main.xml:

Step 2:

Create a class for binding view in recycler view adapter.

Step 3:

Create an item_layout for recycler view item in layout resource.

After that, a class is generated automatically with the name of item_layout i.e. ItemLayoutBinding. In this class, all methods are generated from the variable name in the .xml file.

So there are two methods in ItemLayoutBinding

1. setItem

2. setItemClickListener

Step 4:

Create an adapter for recycler view items.

Step 5:

Init Adapter in Activity class

You can also read our blogs on Android:

1: Android Navigation Component – Android Jetpack

2: Offline Content Storage and Sync with Server when Modified

3: Custom Camera using SurfaceView

4: Capture Image on Eye Blink

InnovationM is a globally renowned Android app development company in India that caters to a strong & secure Android app development, iOS app development, hybrid app development services. Our commitment & engagement towards our target gives us brighter in the world of technology and has led us to establish success stories consecutively which makes us the best iOS app development company in India. We are also rated as the best Mobile app development company in India.

Thanks for giving your valuable time. Keep reading and keep learning 🙂

Leave a Reply