Data Binding – Basics

Reading Time: 9 minutes

It is a common tasks for an Android developer to link the business logic to the user interface. These linking can cause in many cases runtime errors and needs tooo long time to implement them. Then, at Google I/O 2018, the Data Binding has been announced.

Data Binding is Android Jetpack component, which allows developers to declaratively bind observable data to UI elements. Hence, it removes many UI framework calls in our activities and fragments, making them simpler and easier to maintain.

In this tutorial we are going to learn about the basics of Data Binding. First we gonna talk about MVVM (Model–View–ViewModel), then we will cover the place of Data Binding inside of this design pattern.

We are going to build a very simple app, which will count the likes, to learn how to integrate the Data Binding library into a newly created Android project. We will learn about

        • Enable Data Binding in our project
        • Convert an existing layout file to one that uses Data Binding
        • Data Binding in Activities
        • Data Binding adapters


First of all, we have talk about MVVM, which stands for Model–View–ViewModel.

Nowdays, MVVM is one of the most loved design pattern. First time the Microsoft team formalized it in 2005, then it was adaptod by the web community.

MVVM is an architectural pattern, which helps for the developers to separate the business logic from the user interface and enhances the separation of concerns. The goal of this design patter is to achive a programming principle, which is “Keeping UI code simple and free of app logic in order to make it easier to manage“.

One key advantage of MVVM is that it offers the right amount of decoupling. Another good thing is that, the learning curve is similar to the other patterns.

MVVM has three main components: Model, View, and ViewModel.

        • Model: The Model represents the data and the business logic of the application.
        • ViewModel: The ViewModel interacts with the model and holds observables, which can be observed by the view.
        • View: The role of View in the MVVM pattern is to observe a ViewModel observable to get data in order to update the elements of the user interface.

In case of Data Binding, this model has a fourth component, which is the Binder. It is the mechanism that links the Views to the ViewModels. The Binder is usually handled by the platform or a third party library. So, the developers don’t have to write it. For Android, we have the Data Binding library.


How Data Binding Works

With data binding we can connect the views in the XML layout with the data objects. The Data Binding Library generates the classes needed for this process.

The layout files, which uses data binding are different. They always start with the tag of <layout>, followed by the <data> tag. After them comes the root ViewGroup. This root ViewGroup contains all the element, what our root view would do, when we don’t use data binding.

After enabling the Data Binding library in our app, then each layout file will have its own generated data binding class. This will be done by the library. These classes will get there names from the layout file in Pascal case, plus the word of Binding at the end.

Let’s look at two examples:

        • acitivity_main.xml -> ActivityMainBinding
        • fragment_change_player_dialog.xml -> FragmentChangePlayerDialogBinding

Basically, Data binding has three main uses

        • Showing data
        • Handling user events
        • Call actions on layout variables

Create a Sample project

After the introduction, we can start to prepare a project, where we will see how does Data Binding works in action.

Step 1 – Start a new project

First of all, we will start a new project. So, launch Android Studio and create a new project.

If you see the “Welcome page” of Android Studio, then click on the “Start a new Android Studio project”.

If you have an open project, then from the “File” menu select “New”, then “New Project”. After thet, this window will popup.

Here select the “Empty Activity” option.

In the next window, we should provide some information about the newly created app.

As always, this tutorial will be written in Kotlin. So select from the dropdown list the Kotlin language.

From the drop down list of the “Minimum SDK” you can select from which SDK version will be useable your project. For now, we gonna leave the default selected, which is API 21.

There is a link, called “Help me choose”. If you click on it, then a colorful figure will show you the different Android versions and their imported innovations.

If you are done, click on the “Finish” button. The build can take few minutes. Be patient! 😉

When the build has been finished, then you should see the open MainActivity:class and next to this the activity_main.xml files. For now you can close both of them.

Step 2 – Enable Data Binding
Before we can start using Data Binding in our project, we have to enable it. We can do it in the Module build.gradle. You can find it in the Project tab from the left side of Android Studio.

In Android view you will have the app and the Gradle Scripts comboboxes. Expand there the Gradle Scripts, then select the Module build.gradle file.

Enable Data Binding

In this file you will see at the beginning some lines of ‘apply’, then the android{} and dependencies{} section. Add the next few lines at the end of the android{} part.

Enable Data Binding

This line will enable the Data Binding for our project.

Before we can sync, we will make 2 more modifications.

Add kapt

Later on in this tutorial, we are going to use Kotlin annotations. For this, we have to add them to the project, which is the kapt. It stends for Kotlin Annotation Process Tool.

At the beginning of the Module build.gradle file paste after the lines, which start with the keyword of ‘apply’.

apply plugin: ‘kotlin-kapt’

Add the lifecycle library

Because in this project we gonna use ViewModel and LiveDatas as well, we should add the their libraries.

The implementation will be also in the Module build.gradle file, but in this case it goes into the dependecies {}.

So, copy and paste the below line at the end of the dependecies {}.

implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’

Finally, click from the top right corner on the Sync Now text and wait until Android Studio will install and enable the above mentioned libraries for our project.

Step 3 – Transforming the XML layout

Next step is to transform our XML  layout to a data binding layout. For this we need to follow the next 3 steps.

      1. We have to wrap the original root view with a <layout> tag.
      2. Then at the beginning, but before the original root view, we should add the variables. It is not always necessery.
      3. Third step is to add the layout expressions to the views, what we defined inside of the original root view.

Let’s see this steps in action.

First, open the activity_main.xml file from the res -> layout folders.

Then, move you mouse to the root view, and press Alt+Enter on Windows or Control/Option+Enter on Mac. This will open up a quick menu, the Show Context Actions menu. There, select to first option, which is “Convert to data binding layout”. The result should look like below.

Layout after convert to use Data Binding
Step 4 – Add some views to the layout

In this tutorial you will learn the basics of Data Binding. Because of this, our layout will contain only 4 views

        • 2 TextViews
        • 1 Button
        • 1 ProgressBar

Copy and paste the below 4 views into the ConstraintLayout.

The body of the ConstraintLayout
Step 5 – Add the ViewModel

Next step is to create ViewModel class for our app. As we have mentioned before, the data and the business logic should be store in the ViewModel. In our case, it won’t be different either.

So, from the left Project tab and in Android view, expand the app option, then the java folder. Inside of the java folder click with the right mouse button on the package.

Then select New form the quick menu and from the submenu the Kotlin file/class option. In the popup window name the class as “LikesViewModel” and press Enter.

After the creation, copy and paste the below code into the LikesViewModel::class.


First, we have to inherite this newly created LikesViewModel::class the ViewModel class. Then, we can add the needed variables, LiveDatas and a method also into its body.

The second point is the target variable, which will set the maximum value of the ProgressBar.

Third is a LiveData. The value of this LiveData will be written in the first TextView, when we open up the app. More precisely, when the AcitivityMain::class will be created.

The next point from the above source code shows the second LiveData. This will store the current likes and will notify the UI, when the number of the likes has been changed.

The last point is a method, which will increase by one the number of the likes, when we tap on the Likes button.

Step 6 – Start using Data Binding in the Activity

Before we can start using the Data Binding in the XML layout, we have to initialize and configure Data Binding in the AcitivityMain::class. So, open it.

In this class you will see the onCreate() method, which was automatically created by Android Studio. Inside of this method you will see two lines. This lines are going to initialize the view for this class.

To start using Data Binding, we have to remove this line:


and repleace it with this:

val binding: ActivityMainBinding =

Note the ActivityMainBinding::class. This is an automatically generated class by Data Binding from the XML layout file in Pascal case. We have talked about this at the beginning of this tutorial.

Note also that, this code uses a Data Binding Library class called DataBindingUtil to set the content view.

Next, we are going to create a member variable lazily for the LikesViewModel. So, copy and paste the below lines before the onCreate() method.

val likesViewModel by lazy {

Here, the lazy keyword means, that the variable will be initialized only, when it is realy needed.

Still the class doesn’t use the Data Binging library, because we have to tell it the owner of the lifecycle and set the used ViewModel.

So, copy and paste the below 2 lines at the end of the onCreate() method.

binding.lifecycleOwner = this
binding.likesViewModel = likesViewModel

After the paste, you will have an error, which tells “Unresolved reference: likeViewModel”. It means in our case, thet we haven’t created this variable inside of the XML layout.

We are going to solve this issue now.

Value Binding

Value Binding refers to the creation of variables for binding classes. It means, if the value of the variables change, then the layouts automatically update as if they were directly observing the results of the code. There are two ways to update values:

        • layout variables: Variables within the <data> tags, what  we have added at the top of the activity_main layout file, describe a property within a data binding layout.
        • layout expressions: We can handle events in views and update or format the data accordingly.
An advice accourding the documentation of Android: The layout expression language gives us a lot of power, but it is best to avoid nesting complex logic inside views. Complex expressions will make your layout harder to read and maintain.

Binding Values in Activities

After the sort description of the Value Binding, we can start implement variables inside of the XML layout file. So, open up the activity_main.xml file from the res -> layout folders.

Create a layout variable

We are going to create the likesViewModel variable inside of the <data> tags. We can do it by using the <variable> tag. This tag has 2 attributes: name and type. The name will specify the name of the variable, to which we can refer. The type can be a primitive type or like in our case, the LikesViewModel with full path.

So, paste the below variable into the <data> tags.

likesViewModel variable
Bind the layout variable

After the creation of the ViewModel and the layout variable, finally we can bind them to the Views inside of the XML layout.

First of all, we are going to bind the tv_name TextView with the name variable from the LikesViewModel. For this, we will use the text attribute of the TextView. As we have talked about earlier, layout variables are used to write layout expressions. Layout expressions are placed in the value of element attributes and they use the @{expression} format. 

So now, add the next line to the tv_name TextView.


After thet the tv_name TextView looks like this:

tv_name TextView

Run the app

Here we go! Run the app at the first time! After the successful build and run, you should see the name of this website. You can change it, if you open the LikesViewModel and there you can change the value of the _name MutableLiveData.

Next chapter

In the next chapter, we are going to handle the user actions also from the XML layout using Data Binding. So, when we click on the btn_like Button, then the number of the likes in the tv_likes TextView gonna be increased and we will visualize it using the ProgressBar.

For this, we are going to use a BindingAdapter. In the adapter we can create our own attributes and actions for the views. It means in our case the TextView and ProgressBar.

See you in the next chapter: DataBinding – BindingAdapter


The source code is available on GitHub

GitHub – DataBindingBasicsDemo


I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂



Follow and like us:
Click to rate this post!
[Total: 1 Average: 5]

3 thoughts on “Data Binding – Basics”

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications