Hey technoz, hope you are doing great. Here I am with the new topic and tutorial on Data Binding library in Android Application. This tutorial will explain everything about what is data binding, how it can help us to reduce boilerplate code and write code efficiently.
Data Binding is like an extension of view binding library because it does what View Binding library does, plus a lot more than that. So, it becomes easy to understand Data Binding if you know View Binding. If you are not familiar with View Binding yet, then I recommend you to first have a look at View Binding library tutorial first. Here is the link for it.
View Binding in Android Tutorial
Okay, so now I assume you are familiar with View Binding. Let us now understand what the Data Binding is.
What is Data Binding?
The Data Binding Library is a support library that allows us to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. It is a part of Android Jetpack component.
If you prefer video tutorial over text, then you can go through the following video tutorial available on YouTube which is more illustrative and useful.
Why use Data Binding in android app?
Data binding library in android allows us two way data flow – from backend class to layout and from layout to backend too. Data binding works with observables such that the layout will be updated as soon as the data is updated. This makes it very efficient solution to use and reduces a lot of boilerplate code. So, Let us understand this practically.
Before moving to the implementation, lets see what we will be building.
Data Binding library in Android Tutorial
Create a new android studio project and inside module build.gradle
file, insert following statement to enable data binding feature in your android app.
android {
...
buildFeatures {
dataBinding true
}
...
}
At first, Sync the project. After it completes, the data binding is enabled in our android project. Same as in case of View Binding, data binding also generates the binding file “ActivityMainBinding” with all references to the UI components.
Build the layout
We now move towards building the UI as shown in above video. Use the following code to create activity_main.xml
.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:layout_margin="8dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Data Binding tutorial from Technopoints"
android:textStyle="bold"
android:textSize="30sp"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal" />
<EditText
android:id="@+id/enter_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Enter text here..."
android:inputType="textPersonName"
app:layout_constraintTop_toBottomOf="@+id/title"
android:textSize="20sp"/>
<Button
android:id="@+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Submit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/enter_text" />
<TextView
android:id="@+id/user_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Entered text appear here..."
android:textSize="20sp"
app:layout_constraintTop_toBottomOf="@+id/submit_button" />
</androidx.constraintlayout.widget.ConstraintLayout>
However, we need to make few changes in above layout. Go to the top of activity_main.xml
, press Alt+Enter
and from the list of options, choose the first one “Convert to data binding layout“. This will wrap whole the layout inside <layout />
tag, and also provides extra <data />
tag at the top. So, replace the above code with following.
<?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="customText"
type="com.example.databindingtutorial.CustomText" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:layout_margin="8dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Data Binding tutorial from Technopoints"
android:textStyle="bold"
android:textSize="30sp"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center_horizontal" />
<EditText
android:id="@+id/enter_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Enter text here..."
android:inputType="textPersonName"
app:layout_constraintTop_toBottomOf="@+id/title"
android:textSize="20sp"/>
<Button
android:id="@+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Submit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/enter_text" />
<TextView
android:id="@+id/user_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Entered text appear here..."
setCustomText="@{customText.customTextfromUser}"
android:textSize="20sp"
app:layout_constraintTop_toBottomOf="@+id/submit_button" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
What are modifications in above code as a part of data binding in android? Well, let me tell those one by one.
-
- As I said above, the whole code snippet is wrapped inside
<layout />
tag. - Inside the
<data />
tag, we have added<variable />
tag which contains variable name inname
field and variable type in thetype
field. we are givingcustomText
as a name to the variable and setting its type as aCustomText
which is a data class that we will be building in the next step (Ignore the error for now). - In the TextView, we have set one
setCustomText
attribute which will be creating through binding adapter. We will study that in the next part (Ignore this error as well for now).
- As I said above, the whole code snippet is wrapped inside
Creating data class
Create a new data class CustomText.kt
follows.
package com.example.databindingtutorial
data class CustomText(
val customTextfromUser : String
)
Create Binding Adapter
What are Binding Adapters?
At first, This is the basic question comes in our mind. Well, Binding Adapters are static methods which makes the required framework calls to set the values. The data binding library let us define the methods to set values and provide our own implementation. We create these methods outside the class and annotate with @BindingAdapter
. Here is the binding adapter we are declaring for this project at the bottom of MainActivity
.
@BindingAdapter("setCustomText")
fun TextView.setCustomText(customText: String) {
this.text = customText
}
The above function is an extension function of TextView class. In this, we are just taking the string input and assigning it to the text context of TextView. This is just for sample, but we can add as much functionality as we want in this function. If you look at the annotation, we have passed some string value setCustomText
inside the parenthesis which data binding library automatically recognizes and we can use the same string as a layout attribute inside our xml layout and assign the string value to it. This function receives that string and executes the code.
Remember the setCustomText
attribute we used in TextView of layout xml file? That will now make sense. We are assigning the value to it as @{customText.customTextfromUser}
. Now, what this means? Let me explain. The customText
is a variable we have declared in layout file which is of CustomText
data type and we are calling customTextfromUser
string variable. In this way, that value will be binded to the customText
attribute and will be passed to the binding adapter. Whenever the data is changed in the class, the value will be automatically updated in the TextView.
Code the MainActivity
Now, lets come to the MainActivity.kt
as follows, to see how we are using the Data Binding.
package com.example.databindingtutorial
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import com.example.databindingtutorial.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
findViewById<TextView>(R.id.title).text = "Data Binding tutorial from Technopoints"
binding.customText = CustomText(binding.enterText.text.toString())
binding.submitButton.setOnClickListener {
binding.customText = CustomText(binding.enterText.text.toString())
}
}
}
@BindingAdapter("setCustomText")
fun TextView.setCustomText(customText: String) {
this.text = customText
}
In the above code, we are declaring one variable binding
of type ActivityMainBinding
and initializing it with DataBindingUtil
. If you look at TextView with id “title” we are referring it using findViewById
and we are doing in on purpose. Because I just wanted to show the difference between using findViewById
and without using it.
In the next line, we are referring customText
attribute using binding
variable and initializing it. While initializing, we are passing the string which is present in the EditText
. In the same way, we are referring the submit button using binding
variable and inside setOnClickListener
event, we are doing the same thing. i.e. again initializing the object CustomText
so that it will replace the string value inside CustomText
with the new one which is entered by the user. And as it is binded by the TextView
, it automatically updates the text. This is how the magic is happening!
Finally, we are all set. Lets try running our data binding in android tutorial app and we will see the output. However, functionality wise, the app is very simple. But, whatever the concepts we have learnt here are important and hopefully this data binding in android app tutorial clarifies these concepts well.
Download Source Code
If you want to jump directly to the code, feel free to download or clone the source code from the following GitHub repository.
Download Source Code
Something extra from me…
Lastly, I would like to offer something extra from my side. Would you like to take it? If yes, then here it is. Technopoints has started its official WhatsApp Group where programming enthusiasts interact with each others, solve doubts, and learn together. There you will be in a group of like-minded people who are eager to learn, share knowledge, ask doubts and solve others doubts too. Additionally, there I share some of the rare programming tips related to Android development, the solution to the challenges I faced while making app projects which look my lot of time and I got stuck on it. With those tips, you will avoid common mistakes and conquer the hurdles of your programming journey.
Agree? Great! here is the invite link:
Click here to join the Technopoints WhatsApp Group!
Of course, It is open for programmers all over the Globe. Lets connect, share knowledge and grow together. See you in the next tutorial soon with another new hot topic. Thanks, Good bye!