Data Binding Part 1 - The Introduction

Data Binding Part 1 - The Introduction

In this articles series, we will be discussing everything you need to know about Data Binding. This series will contain 3 parts. Introduction to data binding, types and uses, binding adapters and binding operators, and lastly, how to use them with ViewModel and LiveData/Flow.

Introduction to Data Binding

Data Binding Library is an Android Library that is used to bind the UI with the Data Source/Layer. It uses a declarative approach rather than programmatically.

When to use Data Binding Over View Binding

When we need to bind only the UI layer and use them for simple cases, we use view binding. On the other hand, Data binding is used for more complex cases. These help in faster development, execution times, and more readable and maintained code.

Types

  • One Way Data Binding - It's a type of data binding where the UI receives the data from the data source.

  • Two Way Data Binding - It's a type of data binding where the UI and data source both can receive the data from each other.

Tutorials

Let's go step by step:

📌Step 1:

Enable the data binding build option in your build.gradle file in the app module, as shown in the following example:

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

📌Step 2:

Go to the XML file you want to bind and click alt+enter to get an option shown below:

Screenshot 2022-08-08 030228.jpg

Click on "convert to data binding layout"

You will see a inside which you will find your layout parent tags. Create a tag just above your layout parent tag.

Create a tag inside tag :

    <data>
        <variable
            name="data"
            type="com.example.projectName.YourDataSource" />
    </data>

📌Step 3:

Suppose you have YourDataSource class holding values named value1 and value2, then you can provide android:text = @{data.value1} and android:text = @{data.value2} on the XML layouts.

So now the value on value1 and value2 will be shown by those layouts bind with it.

Now, you can create a very basic project using data binding. Hope you have learnt something new. Thanks for reading.

Keep learning! 🔥

Did you find this article valuable?

Support Subhadip Das by becoming a sponsor. Any amount is appreciated!