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.
Advantages of Data binding
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{ |
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 |
Step 3: Now open the activity_main.xml file and add the following xml code
<?xml version="1.0" encoding="utf-8"?> <data> <LinearLayout <TextView <EditText </LinearLayout> |
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.
class MainActivity: AppCompatActivity() { private lateinit var binding: ActivityMain override fun onCreate(savedInstanceState: Bundle?) { binding = DataBindingUtil.setContentView(this, R.layout.activity_main) |
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..
After adding the input in Edittext..
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 { |
Step 3: Open activity_main.xml file and add a TextView and a Button Widget.
<TextView <Button |
Above xml code layout will look like:
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) |
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{ |
Final Code of MainActivity.kt file,
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { binding.button.setOnClickListener{ |
Step 5: Now run the app in your emulator or real device, you will get the given output
OUTPUT:
Complete Source Code of Two Way Data Binding Example:
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <data> <LinearLayout <TextView <EditText </LinearLayout> |
MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { binding = DataBindingUtil.setContentView(this, R.layout.activity_main) |
MainViewModel.kt file
import androidx.lifecycle.MutableLiveData class MainViewModel : ViewModel() { val userName = MutableLiveData() |
build.gradle(app) file
plugins { android { defaultConfig { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" buildTypes { dependencies { implementation 'androidx.core:core-ktx:1.7.0' |
Complete Source Code of DataBinding Example:
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <TextView <Button </LinearLayout> |
MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { binding.button.setOnClickListener{ |
build.gradle(app) file
plugins { android { defaultConfig { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" buildTypes { dependencies { implementation 'androidx.core:core-ktx:1.7.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.
<?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">
In the TextView and EditText, bind the value of “text” property with the “userName” (MutableLiveData) property of the ViewModel.
Step 4: Create a new kotlin class file and enter name (MainViewModel) and add the following code:
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.
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..
After adding the input in Edittext..
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:
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:
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"
/>
MainActivity.kt file
MainViewModel.kt file
build.gradle(app) file
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 :
|
|
|
|
1764 Views |