Android DataBinding Example | Enable Data Binding in Android

DataBinding in android is the way to bind the UI components with the business logic. It is the best way to reduce the length of code . This is the latest architecture in android development.

Android DataBinding is the part of Jetpack library in android. It allows us to bind the data resources to the xml layout by reducing the boilerplate code. It save the development time with quality development of the code. Also provides an easy way to interact with the code to the views.

Why do we use DataBinding in android?

It has the following benefits –

  1. Reduce the length of code.
  2. Easy way to interact with UI components.
  3. Save the development time.
  4. Strong readability
  5. Faster.
  6. Powerful.
  7. Less coupling.
  8. Increase performance.

How to Enable DataBinding in Android?

To enable the DataBinding in android use the following code in your build.gradle (Module) file in android project. Use the below code inside the android{ } component.

dataBinding {
enabled = true
}

Like as Below –

dataBinding android
dataBinding android

Remember to use the dataBinding enabling code inside the android { } code in starting or ending the curly braces. Use can also be used anywhere inside the android { } .  After that sync your project to get the dataBinding dependencies in build.gradle file.

Use layout tag in Your XML File

After completing the syncing process, use all tags inside the layout tag in the xml layout file. Means layout tag should be parent tag in your xml file. See the layout tag as below.

<?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:bind="http://schemas.android.com/tools" >

// all tags will be used here
</layout>

How to Use layout tag in XML file see example

Use layout tag in your project’s xml file as below I highlighted the layout tag using red color.

<?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:bind="http://schemas.android.com/tools" >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:gravity="center">

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            app:boxCornerRadiusTopStart="10dp"
            app:boxCornerRadiusBottomEnd="10dp"
            app:boxCornerRadiusBottomStart="10dp"
            app:boxCornerRadiusTopEnd="10dp"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/inputEmail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="18dp"
                android:singleLine="true"
                android:text="@={loginViewModel.userEmail}">

            </com.google.android.material.textfield.TextInputEditText>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:layout_marginTop="10dp"
            app:boxCornerRadiusTopStart="10dp"
            app:boxCornerRadiusBottomEnd="10dp"
            app:boxCornerRadiusBottomStart="10dp"
            app:boxCornerRadiusTopEnd="10dp"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/inputPassword"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="18dp"
                android:singleLine="true"
                android:text="@={loginViewModel.userPassword}">

            </com.google.android.material.textfield.TextInputEditText>

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/buttonLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="Login"
            android:textSize="14dp"
            app:cornerRadius="10dp"
            android:padding="15dp"
            android:textColor="@color/white"
            android:onClick="@{()-> loginViewModel.ButtonClick()}"
            bind:toastMessage="@{loginViewModel.toastMessag}"
       />

    </LinearLayout>
</layout>
 <data>
<variable
name="loginViewModel"
type="com.example.tiktok.viewModel.LoginViewModel" />
</data>

Please note that the below code inside layout tag is used to bind and access the data from ViewModel class which is a part of MVVM. If you want to learn MVVM patterns in android just follow the link.

Another Way to Use layout tag in XML file in android

To wrap all your tags in layout tag, right click on your parent widget -> Show Context Action – > Convert to data binding layout.


How to access The id of a Widget using dataBinding in Android?

How to access The id of a Widget using dataBinding in Android?

After enabling the dataBinding in android and using layout tag in xml file a ActivityBinding file generated automatically. Also a FragmentBinding file generated automatically for fragment.

Create an object of that activity or fragment. Like as below and also bind the layout to the Activity java class or fragment java class. If your xml file is activity_main.xml then the binding class will be ActivityMainBinding and if the fragment xml is fragment_main.xml then the fragment binding class will be FragmentMainBinding.

For MainActivity.java

Like as – Class Binding and its object

private ActivityMainBinding binding;

And bind the layout as below –

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

To access the id of any widget use Binding class object and dott to access that name no need to do findViewByid()

like finding button id from activity_main.xml using dataBinding ass follow –

binding.buttonLogin

Complete Code for ActivityMainBinding

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


import android.view.View;


import com.example.tiktok.databinding.ActivityMainBinding;



public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityMainBinding binding;
   


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

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


         //button id from activity_main.xml
           binding.buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //action here
            }
        });
    }



}

For Fragment

For fragment use following code , you have to create a View variable also

private FragmentYourVideosBinding binding;
private View view;

Bind the fragment layout as below. Use binding object dott getRoot() method.

binding = DataBindingUtil.inflate(inflater, R.layout.fragment_your_videos, container, false);
view = binding.getRoot();
return view;

To access widget id use binding object and dott to find any id same as above for the ActivityBinding.java

Conclusion Of Using DataBinding In Android

In this article i covered only how to enable dataBinding in android and how to access the widgets id. If you learn something from this tutorial please do comment below.

Learn also Android and Flutter for growing your skills.


close

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment