DataBinding is one of the Android architecture components suggest by Android. DataBinding feature enables by adding one line in project Gradle. Writing code by DataBinding can improve the app by removing boilerplate code for data-driven UI and allowing for two-way binding between views and model objects.
For using the binding, the layout XML file should start with a layout tag. When you will clean or rebuild the project, then the compiler will generate the binding Java classes of those layout files which will have layout tags. For example, the file name of the XML file is activity_main.xml. The generated binding Java class will look like this ActivityMainBinding.java.
Another example is, the layout XML file name is adapter_row_test.xml, the generated binding Java class will be AdapterRowTestBinding.java.
Note: If the project does not generate the binding Java class, then make sure, you added the layout tag as the root tag in the XML file and clean or rebuild the project.
Jump to section
- Step-1 (Create a new project)
- Step-2 (Setup Gradle file)
- Step-3 (Changes in Android resources files)
- Step-4 (Example-1)
- Step-5 (Example-2)
- Step-6 (Example-3)
- Step-7 (Download Source Code)
Demo
Step-1 (Create a new project)
Create a new project and select the blank template.
Step-2 (Setup Gradle file)
1- Open the buildl.gradle.xml file and enable the data binding feature and sync the project.
buildFeatures {
dataBinding true
}
2- Add the below Gradles in the dependencies and sync the project again.
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
3- The project Gradle file should look like this
plugins {
id 'com.android.application'
}
android {
compileSdk 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.databindingexample"
minSdk 21
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
dataBinding true
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Step-3 (Changes in Android resources files)
1- Open the colors.xml file and add the below code
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<!-- App colors -->
<color name="color_bg">#121212</color>
<color name="color_tv">#61EBFD</color>
<color name="color_circle_view">#FF0303</color>
<color name="color_dark_black">#1D1D1D</color>
</resources>
2- Go to res=>values and open the strings.xml file and add the below code
<resources>
<string name="app_name">DataBindingExample</string>
<!-- App strings -->
<string name="str_title">Data Binding Example</string>
<string name="str_ob_exp">Observable Example</string>
<string name="str_other_info">Other Info</string>
<string name="str_notification">Notification</string>
<string name="str_total_req">Total Request</string>
<string name="str_req_accepted">Accepted</string>
<string name="btn_observable">Observable Example</string>
<string name="btn_listing_exp">Listing Example</string>
<string name="str_likes">Likes</string>
<string name="str_followings">Followings</string>
<string name="str_followers">Followers</string>
<!-- Observable Example Screen -->
<string name="str_ob_exp_detail">When user will type in these fields then value will automatically change in below textview without using setText method</string>
<string name="tv_name">Name:</string>
<string name="tv_name_hint">Enter name</string>
<string name="tv_phone">Phone:</string>
<string name="tv_phone_hint">Enter phone</string>
<!-- Listing Example Screen -->
<string name="tv_listing">Listing Example With Binding</string>
<string name="tv_username">John</string>
<string name="tv_user_address">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis elementum nisi. Vivamus neque leo, eleifend ut tempus elementum, dictum eget massa</string>
</resources>
3- Create a drawable file for EditText. Navigate the res => drawable => right-click on it => New => Drawable Resource File called bg_edt_field.xml and the below code.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="@color/white"/>
</shape>
4- Similarly, create another drawable resource file named bg_notification.xml and the below code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<size android:width="30dp" android:height="30dp"/>
<stroke android:width="1dp" android:color="@color/color_circle_view"/>
</shape>
5- Create a drawable resource file for the Button background. Navigate the res => drawable => right-click on it => New => Drawable Resource File called bg_btn.xml and add the below code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/color_dark_black" />
<corners android:radius="50dp"/>
<padding android:bottom="5dp" android:top="5dp" android:left="20dp" android:right="20dp"/>
</shape>
Step-4 (Example-1)
In the first example, we will learn how to bind the model in the XML layout file.
1- Create a model class named ProfileM.java. ProfileM.java class will use to bind the data in an XML file by using the variable tag. Add the below code
package com.example.databindingexample;
public class ProfileM {
public String name;
public String likes;
public String followers;
public String followings;
public int notifications;
public int totalReq;
public int acceptedReq;
}
2- Create a new layout file that defines what the profile screen looks like. Navigate res=>layout=>right-click on it=>New=>Layout Resource File called activity_main.xml and add the below code
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="profile"
type="com.example.databindingexample.ProfileM" />
</data>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/color_bg">
<androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/str_title"
android:textColor="@color/color_tv"
android:textSize="24sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imgProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:src="@drawable/profile"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvHeading" />
<TextView
android:id="@+id/tvUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@{profile.name}"
android:textColor="@color/color_tv"
android:textSize="24sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imgProfile" />
<androidx.cardview.widget.CardView
android:id="@+id/cardLikes"
android:layout_width="110dp"
android:layout_height="120dp"
android:layout_marginTop="15dp"
android:elevation="5dp"
app:cardBackgroundColor="@color/color_dark_black"
app:cardCornerRadius="5dp"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toStartOf="@+id/cardFollowers"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toStartOf="@id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvUsername">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvLikesVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{profile.likes}"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toTopOf="@+id/tvLikes"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="@+id/tvLikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_likes"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvLikesVal" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="@+id/cardFollowers"
android:layout_width="110dp"
android:layout_height="120dp"
android:elevation="5dp"
app:cardBackgroundColor="@color/color_dark_black"
app:cardCornerRadius="5dp"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toStartOf="@+id/cardFollowings"
app:layout_constraintStart_toEndOf="@+id/cardLikes"
app:layout_constraintTop_toTopOf="@+id/cardLikes">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvFollowersVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{profile.followers}"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toTopOf="@+id/tvFollowers"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="@+id/tvFollowers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_followers"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvFollowersVal" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="@+id/cardFollowings"
android:layout_width="110dp"
android:layout_height="120dp"
android:elevation="5dp"
app:cardBackgroundColor="@color/color_dark_black"
app:cardCornerRadius="5dp"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toEndOf="@id/rightGuideline"
app:layout_constraintStart_toEndOf="@+id/cardFollowers"
app:layout_constraintTop_toTopOf="@+id/cardLikes">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvFollowingsVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{profile.followings}"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toTopOf="@+id/tvFollowings"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="@+id/tvFollowings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_followers"
android:textColor="@color/color_tv"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvFollowingsVal" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<TextView
android:id="@+id/tvOtherInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/str_other_info"
android:textColor="@color/color_tv"
android:textSize="24sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardLikes" />
<View
android:id="@+id/viewNotification"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="20dp"
android:background="@drawable/bg_notification"
app:layout_constraintEnd_toEndOf="@id/rightGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvOtherInfo" />
<TextView
android:id="@+id/tvNotificationVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{profile.notifications+""}'
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/viewNotification"
app:layout_constraintEnd_toEndOf="@+id/viewNotification"
app:layout_constraintStart_toStartOf="@+id/viewNotification"
app:layout_constraintTop_toTopOf="@+id/viewNotification" />
<TextView
android:id="@+id/tvNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/str_notification"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/tvNotificationVal"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toTopOf="@+id/tvNotificationVal" />
<View
android:id="@+id/viewTotalReq"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="15dp"
android:background="@drawable/bg_notification"
app:layout_constraintEnd_toEndOf="@id/rightGuideline"
app:layout_constraintTop_toBottomOf="@+id/viewNotification" />
<TextView
android:id="@+id/tvTotalReqVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{profile.totalReq+""}'
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/viewTotalReq"
app:layout_constraintEnd_toEndOf="@+id/viewTotalReq"
app:layout_constraintStart_toStartOf="@+id/viewTotalReq"
app:layout_constraintTop_toTopOf="@+id/viewTotalReq" />
<TextView
android:id="@+id/tvTotalReq"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/str_total_req"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/tvTotalReqVal"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toTopOf="@+id/tvTotalReqVal" />
<View
android:id="@+id/viewReqAccepted"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="15dp"
android:background="@drawable/bg_notification"
app:layout_constraintEnd_toEndOf="@id/rightGuideline"
app:layout_constraintTop_toBottomOf="@+id/viewTotalReq" />
<TextView
android:id="@+id/tvReqAcceptedVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{profile.acceptedReq+""}'
android:textColor="@color/white"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@+id/viewReqAccepted"
app:layout_constraintEnd_toEndOf="@+id/viewReqAccepted"
app:layout_constraintStart_toStartOf="@+id/viewReqAccepted"
app:layout_constraintTop_toTopOf="@+id/viewReqAccepted" />
<TextView
android:id="@+id/tvReqAccepted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/str_req_accepted"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/tvReqAcceptedVal"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toTopOf="@+id/tvReqAcceptedVal" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnObservableExample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@drawable/btn_bg"
android:onClick="openObservableActivity"
android:text="@string/btn_observable"
android:textAllCaps="false"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="@+id/rightGuideline"
app:layout_constraintStart_toStartOf="@id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/viewReqAccepted" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnListingExample"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@drawable/btn_bg"
android:onClick="openListingActivity"
android:text="@string/btn_listing_exp"
android:textAllCaps="false"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="@+id/btnObservableExample"
app:layout_constraintStart_toStartOf="@id/btnObservableExample"
app:layout_constraintTop_toBottomOf="@+id/btnObservableExample" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/leftGuideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="20dp" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/rightGuideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_end="20dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</layout>
3- Open the ActivityMain.java file and add the below code. I added comments to understand the code. DataBindUtils is the class of binding that binds the layout file. It will return the ActivityMainBinding.java object initialization. ActivityMainBinding.java will have all the reference of components which has been used in activity_main.xml with ids. If you remember, before binding, we were using the findViewById method for initializing the components or widgets.
package com.example.databindingexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.databindingexample.databinding.ActivityMainBinding;
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);
activityMainBinding.setProfile(prepareDummyDataOfProfile());
}
/**
* set dummy data for user profile
* @return after set the dummy data return the object of profile object class
*/
private ProfileM prepareDummyDataOfProfile(){
ProfileM profileM = new ProfileM();
profileM.name = "John";
profileM.likes = "224k";
profileM.followers = "145k";
profileM.followings = "452k";
profileM.notifications = 3;
profileM.totalReq = 24;
profileM.acceptedReq = 13;
return profileM;
}
/**
* open Observable example screen
* @param view button view
*/
public void openObservableActivity(View view){
startActivity(new Intent(this,ObservableExampleActivity.class));
}
/**
* open Listing example screen
* @param view button view
*/
public void openListingActivity(View view){
startActivity(new Intent(this,ListingExampleActivity.class));
}
}
Step-5 (Example-2)
In this example, we will learn observable patterns.
1- Create a new layout file that defines what the screen looks like. In this file, we will have two EditText fields when the user starts typing then the result will display in a TextView. This will be a simple example of data binding which will bind the result via model in the XML file. Create a layout resource file named activity_observable_example.xml and add the below code
<?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="user"
type="com.example.databindingexample.UserM" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/color_bg">
<TextView
android:id="@+id/tvHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/str_ob_exp"
android:textColor="@color/color_tv"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvDetail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="@string/str_ob_exp_detail"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="@+id/rightGuideline"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvHeading" />
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/tv_name"
android:textColor="@color/color_tv"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvDetail" />
<TextView
android:id="@+id/tvNameVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="@{user.name}"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/tvName"
app:layout_constraintStart_toEndOf="@+id/tvName"
app:layout_constraintTop_toTopOf="@+id/tvName" />
<TextView
android:id="@+id/tvPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/tv_phone"
android:textColor="@color/color_tv"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="@+id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvName" />
<TextView
android:id="@+id/tvPhoneVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="@{user.phone}"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/tvPhone"
app:layout_constraintStart_toEndOf="@+id/tvPhone"
app:layout_constraintTop_toTopOf="@+id/tvPhone" />
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/inputName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="@+id/rightGuideline"
app:layout_constraintStart_toStartOf="@id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/tvPhone">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_edt_field"
android:hint="@string/tv_name_hint"
android:imeOptions="actionNext"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/inputPhone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:layout_constraintEnd_toEndOf="@+id/rightGuideline"
app:layout_constraintStart_toStartOf="@id/leftGuideline"
app:layout_constraintTop_toBottomOf="@+id/inputName">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edtPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_edt_field"
android:hint="@string/tv_phone_hint"
android:imeOptions="actionDone"
android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/leftGuideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="20dp" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/rightGuideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_end="20dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
2- Create a new Java class named UserM.java. This class will have two observable properties name and phone. Add the below code
package com.example.databindingexample;
import androidx.databinding.ObservableField;
import androidx.lifecycle.Observer;
public class UserM {
public ObservableField<String> name = new ObservableField<>("");
public ObservableField<String> phone = new ObservableField<>("");
}
3- Create a new Activity named ObservableExampleActivity.java. Add the below code
package com.example.databindingexample;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.example.databindingexample.databinding.ActivityObservableExampleBinding;
public class ObservableExampleActivity extends AppCompatActivity {
private ActivityObservableExampleBinding activityObservableExampleBinding;
private UserM userM;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityObservableExampleBinding = DataBindingUtil.setContentView(this, R.layout.activity_observable_example);
// init user object
userM = new UserM();
activityObservableExampleBinding.setUser(userM); // set the object of the user to xml. setUser is auto generated method
// apply text change listener on name editfield
activityObservableExampleBinding.edtName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
userM.name.set(s.toString());// when this value will set to this properties then this value will reflect in XML.
// You don't need to use setText method for set the value.
}
@Override
public void afterTextChanged(Editable s) {
}
});
// apply text change listener on phone editfield
activityObservableExampleBinding.edtPhone.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
userM.phone.set(s.toString()); // same like name, value will set to phone when user will starts typing.
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
Step-6 (Example-3)
In the third example, we’re going to learn the use of DataBinding with RecyclerView.
1- Create a new layout file called adapter_lisiting.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">
<androidx.cardview.widget.CardView
android:id="@+id/cardListing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
android:minHeight="140dp"
app:cardBackgroundColor="@color/color_dark_black"
app:cardCornerRadius="5dp"
app:cardMaxElevation="5dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_margin="5dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tv_username"
android:textColor="@color/color_tv"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvUserAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tv_user_address"
android:textColor="@color/white"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvUsername" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
2- Create a new Java Model class called ListingM.java that will hold the data in the adapter listing XML file.
package com.example.databindingexample;
public class ListingM {
private String name;
private String address;
public ListingM(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3- Create a new Java class called AdapterListing.java. Add the below code
package com.example.databindingexample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.example.databindingexample.databinding.AdapterListingBinding;
import java.util.List;
public class AdapterListing extends RecyclerView.Adapter<AdapterListing.ListingMHolder> {
private List<ListingM> listingMList;
private Context _context;
public AdapterListing(List<ListingM> listingMList) {
this.listingMList = listingMList;
}
protected class ListingMHolder extends RecyclerView.ViewHolder {
private AdapterListingBinding listingBinding;
public ListingMHolder(AdapterListingBinding listingBinding) {
super(listingBinding.getRoot());
this.listingBinding = listingBinding;
}
}
@NonNull
@Override
public ListingMHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
_context = parent.getContext();
AdapterListingBinding adapterListingBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.adapter_listing, parent, false);
return new ListingMHolder(adapterListingBinding);
}
@Override
public void onBindViewHolder(@NonNull ListingMHolder holder, int position) {
ListingM listingM = listingMList.get(position);
holder.listingBinding.tvUsername.setText(listingM.getName());
holder.listingBinding.tvUserAddress.setText(listingM.getAddress());
}
@Override
public int getItemCount() {
return listingMList.size();
}
}
4- Create a new Java file called ListingExampleActivity.java. Comments are added inside the code, you can understand. Add the below code
package com.example.databindingexample;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.databindingexample.databinding.ActivityListingExampleBinding;
import java.util.ArrayList;
import java.util.List;
public class ListingExampleActivity extends AppCompatActivity {
private ActivityListingExampleBinding activityListingExampleBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityListingExampleBinding = DataBindingUtil.setContentView(this, R.layout.activity_listing_example);
initRcv();
prepareDummyDataForListing();
}
/**
* init method for setup the linear layout manager class and set this object to recyclerview
*/
private void initRcv() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
activityListingExampleBinding.rcvListing.setLayoutManager(linearLayoutManager);
}
/**
* prepare the dummy data for listing and set this data to adapter for displaying dummy information of user.
* you can change accordingly your logic
*/
private void prepareDummyDataForListing() {
List<ListingM> listingMList = new ArrayList<>();
for (int j = 0; j < 10; j++) {
listingMList.add(new ListingM(getString(R.string.tv_username), getString(R.string.tv_user_address)));
}
AdapterListing adapterListing = new AdapterListing(listingMList);
activityListingExampleBinding.rcvListing.setAdapter(adapterListing);
}
}
Step-7 (Download Source Code)
Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.