Android DataBinding - How to implement DataBinding and Two Way DataBinding in Android Studio using Kotlin.

Last updated Dec 30, 2021


In this android example we will see what is DataBinding, Two way DataBinding and its implementation in Android Studio using Kotlin language.

What is DataBinding?
In Android, Data binding helps you to link your user interface with the model and logic of your application.

  • We can construct binding classes for xml layout files using the Android data binding framework.
  • We may utilise those binding classes to easily employ view components without executing findViewById().
  • We can also utilise layout variables and layout expressions to automatically set and retrieve values from layouts.
  • Data binding is a simple concept to grasp and apply.
     

Advantages of Data binding

  1. Eliminate findViewById()
  2. Update the values automatically.
  3. Very effective for UI Testing.
  4. More readable and maintainable code.
  5. Faster development & execution times.
  6. Well suited for MVVM and MVI architectures.
     

Two Way DataBinding:
The sharing of data between a component class and its layout is referred to as two-way data binding. If you alter data in one location, it will automatically reflate at the other. If you alter the value of an input box, for example, it will also modify the value of an attached property in a component class.


Simple Two Way Data Binding Implementation Example:
Step 1: Create a new Project in android studio.

Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish

 

Step 2: Now, open the app level build.gradle file . 
Add this code part inside the Android block to enable databinding.

buildFeatures{
        dataBinding true
    }

 

Also, add the kotlin-kapt plugin to the plugins block.

id 'kotlin-kapt'

 

Add the viewModel and LiveData Lifecycle dependency in app level build.gradle file and insert inside dependencies

 // ViewModel
 implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
 // LiveData
 implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.0"

 

Step 3: Now open the activity_main.xml file and add the following xml code

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="com.nishajain.databindingkotlin.MainViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="20dp"
        android:background="#F1EAEA"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Your name"
            android:background="#F6D6D6"
            android:text="@={viewModel.userName}"
            android:textSize="30sp"
           />

        <EditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_marginTop="20dp"
            android:hint="Enter your name"
            android:text="@={viewModel.userName}"
            android:textSize="30sp"
            />

    </LinearLayout>
</layout>

 

In the TextView and EditText, bind the value of “text” property with the “userName” (MutableLiveData) property of the ViewModel.

android:text="@={viewModel.userName}"

 

Step 4: Create a new kotlin class file and enter name (MainViewModel) and add the following code:

class MainViewModel : ViewModel() {

    val userName = MutableLiveData()
}

 

Step 5: Go to MainActivity.kt file and add the following code

In MainActivity(or whatever activity) we do 4 common things, when working with Data Binding, ViewModel and LiveData.

  • Create an instance(object) of Data Binding class of the layout.(ActivityMainBinding)
  • Create an instance(object) of ViewModel class.(MainActivityViewModel)
  • Send the ViewModel instance to the Data Binding instance.
  • Set the life cycle owner of the Data Binding instance.

class MainActivity: AppCompatActivity() {

    private lateinit var binding: ActivityMain
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
    }
}

 

Step 6: Now run the app in your emulator or real device you will get the given output:

You will see a blank EditText at first. Type someting on it. Then, you will see the same text on TextView simultaneously. That is the magic of Two way data binding.

Default view, when we run app at first time..

Data Binding Output


After adding the input in Edittext..

Data Binding

 

Simple Implementation of ViewBinding Example:

Step 1: Create a new Project in android studio.

Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish

 

Step 2: Now, open the app level build.gradle file . And add this code part inside the Android block to enable databinding.

buildFeatures {
        viewBinding true
    }

 

Step 3: Open activity_main.xml file and add a TextView and a Button Widget.

     

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="21sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Set"></Button>

 

Above xml code layout will look like:

Android Data Binding Example


Step 4: Go to MainActivity.kt file 

Declare the object reference variable at the top of the class. 

private lateinit var binding: ActivityMainBinding


Then, within the onCreate function, replace the default setContentView(R.layout.activity main) function call with the data binding instance.

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

 

Now, we are ready to use data binding in this class.
So, lets write a simple code to change the text of textView by using clickListener on Button.

binding.button.setOnClickListener{
            binding.textView.text = "Hello Developers!"
        }

 

Final Code of MainActivity.kt file,

 

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener{
            binding.textView.text = "Hello Developers!"
        }
    }
}

 

Step 5: Now run the app in your emulator or real device, you will get the given output

OUTPUT:
 

Android Data Binding Example 2

 

Android Data Binding Example 3



Complete Source Code of Two Way Data Binding Example:

activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="com.nishajain.databindingkotlin.MainViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="20dp"
        android:background="#F1EAEA"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Your name"
            android:background="#F6D6D6"
            android:text="@={viewModel.userName}"
            android:textSize="30sp"
           />

        <EditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_marginTop="20dp"
            android:hint="Enter your name"
            android:text="@={viewModel.userName}"
            android:textSize="30sp"
            />

    </LinearLayout>
</layout>

 

MainActivity.kt file 

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.nishajain.databindingkotlin.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
    }
}

 

MainViewModel.kt file

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class MainViewModel : ViewModel() {

    val userName = MutableLiveData()
}


build.gradle(app) file

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.nishajain.databindingkotlin"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
   
    buildFeatures{
        dataBinding true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'androidx.databinding:databinding-runtime:7.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.0"
}



Complete Source Code of DataBinding Example:

activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:background="#F1E1E1"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="21sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Set"></Button>

</LinearLayout>

 

MainActivity.kt file

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.nishajain.databindingkotlin.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener{
            binding.textView.text = "Hello Developers!"
        }
    }
}

 

build.gradle(app) file

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.databindingkotlin"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildFeatures {
        viewBinding true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

 

Conclusion: In this example we have covered what is DataBinding, Two Way Data Binding and its implementation with example in Android Studio using Kotlin Language.


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

723 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions