This is the first part of Android Jetpack Sunflower Gardening Project. If you want to read intro for this project visit here.
Here we are going to discuss about Live Data, View Model with Data Binding library.
Live Data is an observable data holder class, which fire an event when data gets changed. It also survive configuration changes. Live Data consider an Observer class object.
Data Binding Library is one of the greatest library provided by Android. Use ViewModel with Android Binding Library to get complete benefit. You have to forget about Butter Knife or similar library if you are using so.
ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
Let's start....
Create a new Android Project with Empty Activity.
Be sure to use Kotlin as default language and use android.x* artifacts.Now refract(Shift + F6) the MainActivity to GardenActivity. And refract activity_main.xml to activity_garden.xml {It will help in avoiding confusion with sample app.}
Click MainActivity and press Shift+F6 to refract it.
Apply the same process for activity_main.xml.
Now enable data binding library in your project gradle app module build.gradle:
android {
...
dataBinding {
enabled true
}
}
Add ViewModel extension dependency to app module build.gradle
//Lifecycle component:
implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
Add this line to
build.gradle (app): apply plugin: 'kotlin-kapt'In
build.gradle(project), inside buildscript add lifecycleVersion = '2.1.0-alpha04'Complete
build.gradle(app):apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.masoomyf.sunflowerexample"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
dataBinding {
enabled = true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
//Lifecycle component:
implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
}
Complete
build.gradle(project):// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext{
kotlin_version = '1.3.30'
lifecycleVersion = '2.1.0-alpha04'
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0-alpha13'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Now I am going to show you a demo for Live Data, Databinding and View Model {Remember: This is not going to be use in future. This is just a demo}
Add a Button and a TextView to the activity_garden.xml.
Goto activity_garden.xml (text mode), place the cursor on line one and press Alt+Enter, to convert layout to data binding layout.
After adding button, textview and converting layout to data binding layout, your code should look like this:
<?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>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GardenActivity">
<TextView
android:id="@+id/tvCounter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="@+id/btnReset"
app:layout_constraintEnd_toStartOf="@+id/btnReset"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/btnReset" />
<Button
android:id="@+id/btnReset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="Reset"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Inside data tag, we put the layout variable.
Layout variables are used to write layout expressions. Layout expressions are placed in the value of element attributes and they use the
@{expression} format. Here are some examples
// Some examples of complex layout expressions
android:text="@{String.valueOf(index + 1)}"
android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"
android:transitionName='@{"image_" + id}'
// Bind the name property of the viewmodel to the text attribute
android:text="@{viewmodel.name}"
// Bind the nameVisible property of the viewmodel to the visibility attribute
android:visibility="@{viewmodel.nameVisible}"
// Call the onLike() method on the viewmodel when the View is clicked.
android:onClick="@{() -> viewmodel.onLike()}"
Time to create a view model for our layout.
Create a new kotlin classTestViewModel inside a new package name viewmodels.Extends this class to
ViewModel and add the following code:class TestViewModel: ViewModel() {
//Creating int type live data and initialize it to zero
val counter = MutableLiveData()
.apply { value = 0 }
//A reset method that will reset the counter,.
fun reset(){
counter.value = 0
}
}
Add the view model to our garden layout. Inside data tag, add a new tag variable.
<variable
name="viewModel"
type="com.masoomyf.sunflowerexample.viewmodels.TestViewModel" />
Inside text view, replace
android:text to the following code:android:text="@{viewModel.counter}"
now





hi there, thank you for your explanation! why don't you continue this project?
ReplyDelete