Architecture Components

Data Binding in Android Tutorial

Data Binding library helps us to bind the observable data to the UI elements and tell you everything about it in this article, and will implemented in a demo application as well.

What is Data Binding

It is a part of android architecture components. Today data binding is a hot buzzword Android developers quite recently. It is a support library that allows us to bind the UI components in the layout to data resources and this is done in a declaration format rather than doing it programmatically. So it reduces the boilerplate code a lot.

It helps us to keep the code very organised since it has a definite project architecture structure. With the help of Data Binding the no more need of findViewById(). It offers flexibility and compatibility and It is supported API level 14 or higher. Mean you can use it with devices Running Android 4.0 ( level 14 or higher).

Data Binding in Android Sample App

Data Binding Sample Application

Let’s move to Android studio and start getting our hands dirty with data binding. Go to file menu and create a new project with default template.


Now to enable data Binding in our Android project the first thing we need to make sure that we have support repository in the Android SDK manager.

To ensure you have to go tools => SDK manager => switch to tab SDK tools and make sure you have Android support repository if you don’t check the checkbox and hit apply. such as below snapshot

data binding in android,
data binding in android tutorial,
data binding in android studio,
support repository

Configure your app to use the data binding

Open the app/build.gradle, Then you have to add these line of code inside the android tags in gradle and sync project

 dataBinding {
        enabled = true
 }

In case if this doesn’t work refer the android official documentation

Layout and Binding Expression in Data Binding

1. Create XML layout inside the <layout/>.

We use data binding expression for connecting to layout with data resource file. In this demo, We are taking the example of user profile screen. So we will understand the core working of data binding. Open the layout (XML) file activity_main and replace the root with layout tag and place all tags inside to layout tags.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <RelativeLayout
            android:id="@+id/rellay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/grad"
            android:paddingBottom="20dp">

            <RelativeLayout
                android:id="@+id/imgUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="@drawable/circle_border">

                <ImageView
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_margin="9dp"
                    android:adjustViewBounds="true"
                    android:background="@drawable/circle"
                    android:padding="3dp"
                    android:scaleType="centerInside"
                    android:src="@drawable/profile_pic" />

            </RelativeLayout>

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgUser"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="15sp"
                android:fontFamily="@font/montserrat"
                android:text="Maria Montessori "
                android:textColor="@color/white"
                android:textSize="32sp" />

            <TextView
                android:id="@+id/tv_address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_name"
                android:layout_centerHorizontal="true"
                android:fontFamily="@font/montserrat"
                android:text="new york, usa"
                android:textAllCaps="true"
                android:textColor="@color/address"
                android:textSize="14sp" />

        </RelativeLayout>

        <LinearLayout
            android:id="@+id/linlay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/rellay1"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@color/followersBg"
                android:gravity="center"
                android:paddingTop="5dp"
                android:paddingBottom="5dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tvFollowers"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="453K"

                        android:textColor="@color/white"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="followers"
                        android:textAllCaps="true"
                        android:textColor="@color/white"
                        android:textSize="13sp" />

                </LinearLayout>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@color/followingBg"
                android:gravity="center"
                android:paddingTop="5dp"
                android:paddingBottom="5dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tvfollowing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="873"
                        android:textColor="@color/white"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="following"
                        android:textAllCaps="true"
                        android:textColor="@color/white"
                        android:textSize="13sp" />

                </LinearLayout>

            </RelativeLayout>

        </LinearLayout>
    </RelativeLayout>
</layout>

Here is layout tag tells the Android Framework that this activity main.xml then use data binding of binding class is automatically generated for each layout file by the father name(Our case is MainActivity) of the class is based on the name of the layout file and added the Binding suffix. That means the name of autogenerated file is (for activity_main.xml ) MainActivityBinding.

Generated file name is => ActivityName in Capital Latter + Binding suffix


In case file is not generate rebuild the project. still doesn’t work go to files invalidate cache and restart

2. Replace the traditional setContentView() to DataBindingUtil.setContentView() in Activity

Open the MainActivity, create a object of DataBindingUtils class and replace the traditional setContentView() to DataBindingUtil.setContentView() like this

package com.wave.databindingexample;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.wave.databindingexample.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    }
}

Now run the project and see, So here is our app up and running. now you able to set layout using data binding.

Let’s us see how to data bind with Views and Widget using data binding

Now we will bind view using data binding into our MainActivity. Mean we will access all views in our Activity using binding instance. Let’s see the below code

package com.wave.databindingexample;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.wave.databindingexample.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        binding.tvName.setText("Monika Sharma");
        binding.tvAddress.setText("251 mansarovar Jaipur | India ");
        binding.tvFollowers.setText("240K");
        binding.tvfollowing.setText("324K");
    }
}

Now run the application. You will see the data have been changed as your expectations. The conclusion is we have successfully use the data binding instance to populate to widget in UI.

Bind the data object with Views

Let’s see how can we bind the data objects with views. To do that in the App java go src and create a class named is User.java which will be a data class. In that class create some properties such as name, address, followings and followers.

package com.wave.databindingexample;

/**
 * Created on : Mar 16, 2019
 * Author     : AndroidWave
 */
public class User {
    private String name;
    private String address;
    private String followerCount;
    private String followingCount;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getFollowerCount() {
        return followerCount;
    }

    public void setFollowerCount(String followerCount) {
        this.followerCount = followerCount;
    }

    public String getFollowingCount() {
        return followingCount;
    }

    public void setFollowingCount(String followingCount) {
        this.followingCount = followingCount;
    }
}

Declare data tag in activity_main.xml

Now move to the activity_main.xml, You have to make some changes in XML. We will use <data/> tag to define a variable inside the <layout> which is used the user data object. So variable name I keep it as user and data object type is User. Meanwhile, you have to set data to TextView using this user data object like this.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="user"
            type="com.wave.databindingexample.User" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <RelativeLayout
            android:id="@+id/rellay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/grad"
            android:paddingBottom="20dp">

            <RelativeLayout
                android:id="@+id/imgUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="@drawable/circle_border">

                <ImageView
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_margin="9dp"
                    android:adjustViewBounds="true"
                    android:background="@drawable/circle"
                    android:padding="3dp"
                    android:scaleType="centerInside"
                    android:src="@drawable/profile_pic" />

            </RelativeLayout>

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgUser"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="15sp"
                android:fontFamily="@font/montserrat"
                android:text="@{user.name, default=Name}"
                android:textColor="@color/white"
                android:textSize="32sp" />

            <TextView
                android:id="@+id/tv_address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_name"
                android:layout_centerHorizontal="true"
                android:fontFamily="@font/montserrat"
                android:text="@{user.address, default=Address}"
                android:textAllCaps="true"
                android:textColor="@color/address"
                android:textSize="14sp" />

        </RelativeLayout>

        <LinearLayout
            android:id="@+id/linlay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/rellay1"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@color/followersBg"
                android:gravity="center"
                android:paddingTop="5dp"
                android:paddingBottom="5dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tvFollowers"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text='@{user.followerCount, default="0 K"}'

                        android:textColor="@color/white"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="followers"
                        android:textAllCaps="true"
                        android:textColor="@color/white"
                        android:textSize="13sp" />

                </LinearLayout>

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@color/followingBg"
                android:gravity="center"
                android:paddingTop="5dp"
                android:paddingBottom="5dp">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/tvfollowing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text='@{user.followingCount, default="0 K"}'
                        android:textColor="@color/white"
                        android:textSize="25sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/montserrat"
                        android:text="following"
                        android:textAllCaps="true"
                        android:textColor="@color/white"
                        android:textSize="13sp" />

                </LinearLayout>

            </RelativeLayout>

        </LinearLayout>
    </RelativeLayout>
    <!--    ui design -->
</layout>

Initialise User data object in Activity

For doing that open the MainActivity and set data source to the binding object like this.

package com.wave.databindingexample;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.wave.databindingexample.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

//        binding.tvName.setText("Monika Sharma");
//        binding.tvAddress.setText("251 mansarovar Jaipur | India ");
//        binding.tvFollowers.setText("240K");
//        binding.tvfollowing.setText("324K");

        binding.setUser(new User("Monika Sharma", "251 mansarovar Jaipur | India ", "240K", "324K"));
    }
}

Now run the application and check if it work fine. So here again our app up and run. You have see the update data that comes from data object which we have define in our layout file.

Event handling using Data Binding

Now let us consider some event handling using data binding. For to do create a new class named EventHandler and expose onButtonClick()

package com.wave.databindingexample;

import android.content.Context;
import android.widget.Toast;

/**
 * Created on : Mar 16, 2019
 * Author     : AndroidWave
 */
public class EventHandler {
    Context mContext;


    public EventHandler(Context mContext) {
        this.mContext = mContext;
    }

    public void onButtonClick(String name) {
        Toast.makeText(mContext, "Now you are following " + name, Toast.LENGTH_SHORT).show();
    }
}

Meanwhile, make I have made few changes in our layout file. I have added a follow button in the activity layout and define the variable to the event handler. After that set the button onClick functions like => android:onClick=”@{() -> handler.onButtonClick(user.name)}” . Finally, the layout xml looks like this

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="user"
            type="com.wave.databindingexample.User" />

        <variable
            name="handler"
            type="com.wave.databindingexample.EventHandler" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_