Introduction to Data Binding For Android

Oya Canlı
Enpassio
Published in
5 min readJun 18, 2019

Android Data Binding Library is a very powerful support library which makes it possible to bind data to views in a declarative format using xml layouts, instead of setting them programmatically. At the least, it can save you from those expensive and boilerplate calls to findViewById. But when used to its whole power, it can significantly shrink your code.

In this series of articles, I’ll try to show you how to use Android Data Binding Library, beginning from the very basics and gradually moving towards more advanced concepts. Here is an overview of the five articles:

  1. Introduction to Data Binding For Android (You’re here): In this first article, we will begin by setting-up data binding in our project and changing our layouts for binding views and accessing them from Java/Kotlin code.
  2. Data Tags, Binding Expressions, Imports and Include: In the second part of the series, we will see how to set data to views with data binding and how to use imports and layout expressions in xml. We’ll also see what to do when we use <include>
  3. RecyclerViews and Event Handling with Data Binding: In the third part, we will deal with event handling with data binding and we will see how to use data binding in RecyclerView item layouts.
  4. Binding Adapters and Observable Objects: In the fourth part, we will learn how to create custom binding adapters and how to work with observable objects.
  5. Two-Way Data Binding: Finally, we will see how to use two-way data binding. We will learn about inverse binding adapters and inverse methods.

As Enpassio team, we created three samples for you, with various difficulty levels. All samples have both Kotlin and Java versions. First one, Data Binding with Recyclerview, is a bare-bones sample, designed for complete beginners. Second one, Data Binding with News Api, contains some Android Jetpack components and a few more advanced data binding concepts. And the third one, Two-Way Databinding, demonstrates the use of two-way data binding.

I’ll share snippets from the samples along the way, but you can consult the samples whenever you wish. This github repository contains both Java and Kotlin versions of all samples.

A. Set-up

  1. Enable data binding from gradle scripts, by adding the following piece of code inside the android block of the module level build.gradle file.
android {
buildFeatures {
dataBinding true
}
...
}

If you’re using Kotlin, add also kotlin-kapt plugin, if you don’t already have it. You’ll need this later when you’ll use annotations.

apply plugin: 'kotlin-kapt'

2. Data binding is supported for the Android Plugin for Gradle version 1.5.0 and higher. But it is highly recommended to use the latest versions of gradle. The versions before 3.2 was using by default the first version of data binding, which was infamous for its false data binding errors. After each modification you had to clean-rebuild and occasionally even invalidate caches and restart Android Studio. Sometimes you had to manually import generated classes. These problems are solved with version 2. And with later versions of gradle, build performance and facility of the usage was further improved.

B. Bind your views

Enabling data binding doesn’t automatically generate binding implementations for all layouts. You can consider it as a flexibility the library is providing: you don’t have to use data binding in all of your layouts. May be you want to try it out only on your most crowded layout, to get rid of long lines of findViewById() calls, it is totally fine.

In order to let the library know that you want to implement data binding for a specific layout, you need to make some small changes in that layout.

Let’s suppose you have a layout like this:

You’ll need to wrap your root layout inside <layout> tags as follows:

Note that you’ll need to move the namespace declarations into the layout tag, if you do these changes manually.

However, since Android Studio is very kind and helpful, it can do these changes for you. Click on your root tag and while your caret is over the root tag, hit “Alt + Enter”. Android Studio will suggest converting your layout to data binding layout (This is a magic shortcut of Android Studio which always comes with great suggestions)

This small change is enough for generating a binding class for this layout and binding the views inside. When you rebuild your project, Android Studio will generate a binding implementation class for this layout and name it by converting the name of the layout to pascal case and adding Binding suffix. For instance, if the layout file is named as activity_main.xml, generated binding class will be named as ActivityMainBinding. If your layout is named as fragment_list.xml, your binding class will be named as FragmentListBinding.

Optional: It is possible to change these names, if you wish. You simply need to declare a class name inside data tags as follows (we will talk more about <data> tags later):

The layout file above is called “app_bar_main.xml”. By default, the binding class generated from this file would be named “AppBarMainBinding”. But I changed it as “NewsListBinding”. This is just to demonstrate that it is possible to rename the file names of the generated binding classes. It is not necessary.

C. Access from Java/Kotlin code:

In order to have access to these views from your Java/Kotlin code, you’ll need an instance of the generated binding class. It is recommended to get this instance while inflating the layout.

If the layout belongs to an activity, you can use one of the following methods to achieve this. You can get the instance while calling setContentView:

//Java
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
//Kotlin
val binding : ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

Or, you can get the instance by using the inflate method of the generated binding class:

//Java
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
//Kotlin
val binding : ActivityMainBinding = ActivityMainBinding.inflate(getLayoutInflater())

If it is a fragment layout or the layout of a list item, you can do it by using the inflate() method of the DataBindingUtil class:

//Java
FragmentListBinding binding = DataBindingUtil.inflate( inflater, R.layout.fragment_list, container, false);

//Kotlin
val binding = DataBindingUtil.inflate(inflater, R.layout.fragment_list, container, false)

Or, again, you can use the inflate method of the generated binding class:

//Java
FragmentListBinding binding = FragmentListBinding.inflate(inflater, R.layout.fragment_list, container, false);

//Kotlin:
val binding = FragmentListBinding.inflate(inflater, R.layout.fragment_list, container, false)

Just in case, if the compiler cannot find your generated binding class, here are a few tips:

If you have just added a new layout, you should rebuild your project. If you renamed the layout, again, you should rebuild your project. Small changes over the layout, like adding a variable or expression doesn’t require rebuild anymore, but whenever you encounter an unexpected problem after a change, try rebuilding first.

Once you have an instance of your binding object, you will have access to the views on that layout as properties of that binding object. Each view will be named according to their view ids, converted to pascal case. For instance, if you have a view with the id “product_name” then you can call it on your binding object like:

binding.productName

That’s it. You can erase all those findViewById calls and directly call your views from your binding object whenever needed. If that was all you expected from Android Data Binding Library, you can stop at this point. However, if you want to harvest the real power of the library, you can continue the journey here.

--

--