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

android {
    
    .....
    .....
    
    dataBinding {
        enabled = true
    }
}

Step 2:

In creating a class for binding view

public class Shape {
    public String name;
    public String formula;

    public Shape(String name, String formula) {
        this.name = name;
        this.formula = formula;
    }
}

For Callback:

package com.example.databindingdemo;

public interface ViewClickListener {
    void onViewClick(Object view, Object model);
}

Step 3:

Add the binding class in XML layout.

fileName activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="ShapeData"
            type="com.example.databindingdemo.Shape" />

        // For clicklistener...

        <variable
            name="viewCallback"
            type="com.example.databindingdemo.ViewClickListener" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@{ShapeData.name}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@{ShapeData.formula}" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{(view)-> viewCallback.onViewClick(view, ShapeData)}"
            android:text="Click me" />

    </LinearLayout>

</layout>


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:

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding activityMainBinding;

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

        insertDataToUI();
    }

    private void insertDataToUI() {
        ShapeData shapeData = new ShapeData("Name: Rectangle", "Formula: lenght * height");

        activityMainBinding.setShapeData(shapeData);  //setShapeData is autogenerated method...

        activityMainBinding.setViewCallback(item);  //setViewCallback is autogenerated method...
    }


    ViewClickListener item = new ViewClickListener() {
        @Override
        public void onViewClick(Object view, Object model) {
            ShapeData shape = (ShapeData) model;
            Toast.makeText(MainActivity.this, shape.name + " and " + shape.formula, Toast.LENGTH_SHORT).show();
        }
    };

Binding Recyclerview with adapter

Step 1:

Add the following dependency in build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.databindingdemo"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

FileName activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="itemAdapter"
            type="com.example.databindingdemo.ItemAdpter" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvItem"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adapter="@{itemAdapter}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/item_model" />

    </LinearLayout>

</layout>

Step 2:

Create a class for binding view in recycler view adapter.

public class UserDetail {
    public String name;
    public String age;

    public UserDetail(String name, String age) {
        this.name = name;
        this.age = age;
    }
}

Step 3:

Create an item_layout for recycler view item in layout resource.

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="item"
            type="com.example.databindingdemo.UserDetail" />

        <variable
            name="itemClickListener"
            type="com.example.databindingdemo.ViewClickListener" />

    </data>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical"
        app:cardElevation="3dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="90dp"
            android:gravity="center">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@{item.name}" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="@{item.age}" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@{(view) -> itemClickListener.onViewClick(view, item)}"
                android:text="Click" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</layout>

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.

package com.example.databindingdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.databindingdemo.databinding.ItemLayoutBinding;

public class ItemAdpter extends RecyclerView.Adapter<ItemAdpter.ItemViewHolder> {
    private Context context;
    private String name[] = {"John", "Jelina", "Jonathan", "Marchel", "Richy"};
    private String age[] = {"23", "26", "64", "20", "22"};

    public ItemAdpter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemLayoutBinding itemLayoutBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_layout, parent, false);
        return new ItemViewHolder(itemLayoutBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull final ItemViewHolder holder, final int position) {
        final UserDetail userDetail = new UserDetail(name[position], age[position]);
        holder.bindItem(userDetail);

        holder.itemLayoutBinding.setItemClickListener(new ViewClickListener() {
            @Override
            public void onViewClick(Object view, Object model) {
                UserDetail user = (UserDetail) model;
                Toast.makeText(context, "Hello " + user.name + ", You are " + user.age + " year old.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return name.length;
    }

    public class ItemViewHolder extends RecyclerView.ViewHolder {
        private ItemLayoutBinding itemLayoutBinding;

        public ItemViewHolder(@NonNull ItemLayoutBinding itemView) {
            super(itemView.getRoot());
            this.itemLayoutBinding = itemView;
        }

        public void bindItem(UserDetail item) {
            itemLayoutBinding.setItem(item);
        }
    }
}

Step 5:

Init Adapter in Activity class

package com.example.databindingdemo;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.example.databindingdemo.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
private ActivityMainBinding activityMainBinding;
private ItemAdpter itemAdpter;

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

initialisedRecyclerView();
}

private void initialisedRecyclerView() {
itemAdpter = new ItemAdpter(this);
activityMainBinding.setItemAdapter(itemAdpter);
}
}

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