Data Binding
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
Generally, we are using the findViewById() function to obtain references to views.
But, every time we do so , Android system has to go through the view hierarchy and find it at runtime.
Moreover , there can be many layouts and hundreds of views in a larger Android application.
Therefore, system will have to go through the view hierarchy again and again .
That is a very inefficient and resource consuming process.
So, Google introduced Android data binding library as a solution for that problem.
It generates a corresponding binding class for each xml layout.
After that, we can easily use an instance(object) of that binding class to set values to and get values from view components.
Advantages of Data binding
- Eliminate findViewById()
- Update the values automatically.(doesn’t have to keep track of all the ways a value can be updated)
- Very effective for UI Testing.
- More readable code.
- More maintainable code.
- Faster development times.
- Faster execution times.
- Errors can be found during the compile time.
- Well suited for MVVM and MVI architectures.
Step 1: Create a New Project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- Name the application at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
Step 2. Enable DataBinding
Get Çağla Çorak’s stories in your inbox
Join Medium for free to get updates from this writer.
Navigate to Gradle Scripts > gradle.scripts(module) and add the following code to it.
buildFeatures{
dataBinding = true
}Step 3. Working on XML files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 4. Working on Java files
Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.
The name of the layout we wrapped with layout tags is activity_main.
Using that , android data binding library will create a binding class with the name of ActivityMainBinding.
Data binding library takes the name of the xml layout, make first letter of each name capital, removes underscore and adds “Binding” to the end.
No more findViewById()
Since we are using databinding we don’t need to find views using id.
How data binding actually works?
- For each xml layout file we marked with <layout></layout> tags, data binding library generates a binding class.
- This binding class facilitates us to set values to and get values from each property in the layout.
See you :)









