The Wayback Machine - https://web.archive.org/web/20240618004025/https://www.geeksforgeeks.org/data-binding-in-android-with-example/
Open In App

Data Binding in Android with Example

Last Updated : 28 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

What we are going to build in this article?

Here is a sample video of what we are going to build in this project. Note that we are going to make this project in Java language.


Step-by-Step Implementation

Step 1: Create a New Project

  • Open a New Project.
  • We will be working on Empty Activity with language such 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.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?  


Step 2. Enable DataBinding

Navigate to Gradle Scripts > gradle.scripts(module) and add the following code to it.

gradle_module_java

Add the below code snippet to the build.gradle file to activate dataBinding in the application:

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.

activity_main_Java

Below is the code for the activity_main.xml file.

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">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="16dp"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Data Binding\nFor Activity"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="@color/design_default_color_primary"
            android:gravity="center" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_input"
            android:hint="Enter text"
            android:padding="12dp"
            android:layout_marginTop="16dp"
            android:background="@android:drawable/editbox_background" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/bt_submit"
            android:text="Submit"
            android:layout_gravity="center"
            android:layout_marginTop="8dp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tv_output"
            android:textSize="32sp"
            android:textStyle="bold"
            android:gravity="center"
            android:layout_marginTop="8dp" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/fragment"
            android:layout_marginTop="16dp" />


    </LinearLayout>
</layout>


Navigate to app > right-click > new > fragment > BlankFragment and name it as “MainFragement”:

fragment_main

Use the following code in fragment_main.xml file:

fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"> 
    
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_height="match_parent"
            tools:context=".MainFragment">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Data Binding\nFor Fragment"
                android:textSize="24sp"
                android:textStyle="bold"
                android:textColor="@color/design_default_color_primary"
                android:gravity="center" />
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_input"
                android:hint="Enter text"
                android:padding="12dp"
                android:layout_marginTop="16dp"
                android:background="@android:drawable/editbox_background" />
    
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/bt_submit"
                android:text="submit"
                android:layout_marginTop="8dp" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tv_output"
                android:textSize="32sp"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_marginTop="8dp" />
    
        </LinearLayout>
</layout>


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.

MainActivity.java
package com.example.databinding;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingComponent;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

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

import com.example.databinding.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    // Initialize variables
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Assign variable
        binding= DataBindingUtil.setContentView(this,R.layout.activity_main);

        binding.btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get text from edit text
                String sText=binding.etInput.getText().toString().trim();

                // Check condition
                if(!sText.equals(""))
                {
                    // when text is not empty
                    // set text on text view
                    binding.tvOutput.setText(sText);
                }
                else
                {
                    // When text is empty
                    // Display Toast
                    Toast.makeText(getApplicationContext()
                    ,"Please enter text",Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Initialize fragment
        Fragment fragment=new MainFragment();

        // Commit fragment
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment,fragment).commit();
    }
}


Navigate to the MainFragment.java file and use the following code in it.

MainFragment

Comments are added to the code to have a better understanding.

MainFragment.java
package com.example.databinding;

import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.databinding.databinding.FragmentMainBinding;

public class MainFragment extends Fragment {

    // Initialize variable
    private FragmentMainBinding binding;
    private View view;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public MainFragment() {
    // Required empty public constructor
    }

    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Assign variable
        binding= DataBindingUtil.inflate(inflater,R.layout.fragment_main,container,false);
        view=binding.getRoot();

        binding.btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get text from edit text
                String sText=binding.etInput.getText().toString().trim();

                // Check condition
                if(!sText.equals(""))
                {
                    // When text is not empty
                    // Set text on text view
                    binding.tvOutput.setText(sText);
                }
                else
                {
                    // When text is empty
                    // Display Toast
                    Toast.makeText(view.getContext(),
                            "Please enter text",Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Return view
        return view;
    }
}


Here is the final output of our application.

Output:

Output_Data_Binding_Java


Similar Reads

Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
Data Binding with LiveData in Android
Prerequisite: DataBindingLiveData and ViewModel So, Why we are using Data binding with LiveData? Actually, If we want our views to directly communicate with ViewModel (Data source), we can do that simply without using LiveData. But if data changes in ViewModel it won't reflect its View. This is where we can take the help of LiveData, to automatical
2 min read
Data Binding with ViewModel in Android
DataBinding is one of the most important concepts to really improve the performance of your Android Application It plays a vital role in the maintenance of the many Android Architectures. In this article, we will learn about DataBinding in ViewModel In Android. Benefits of integrating Data binding in ViewModel There are many benefits of using two i
5 min read
View Binding in Android Jetpack
View Binding is one of the best features which provides the views to bind with the activity which is ongoing. Replacing the findViewById() method, hence reducing the boilerplate code, generated the instances of the views of the current layout. And most important feature about the View Binding is it's always null safe. In this article detailed it's
4 min read
View Binding with Fragments in Android Jetpack
In the Previous article View Binding in Android Jetpack, it's been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same
6 min read
How to Use View Binding in RecyclerView Adapter Class in Android?
View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note that we are going to implement this project using the Kotlin language. Step by Step Implementation Step 1:
5 min read
How to Implement View Binding Inside Dialog in Android?
In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout. What we
4 min read
Synthetic Binding in Android
In android application development, for every view in the XML, we need to get an instance of that view to get access to it for doing any operation on it, like changing any property of a view. This is a very common requirement in any android application development cycle. There are main two ways of android development. Data Binding: Data Binding Lib
3 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
How to Access Data or Data Folder in an Android Device?
Android Operating System offers several storage methods to save your app data and images, audio files, docs, etc. App-specific storage: It only stores the data that is used by your App.Shared Storage: It stores files including images and documents.Databases: It provides a local Database for your app (for example, SQLite) In this project, we access
7 min read