Lesson 8 - App Architecture (UI Layer)
Lesson 8 - App Architecture (UI Layer)
Lesson 8 - App Architecture (UI Layer)
App architecture
(UI layer)
res/
layout
UI Controller
(Activity/Fragment
ViewModel
)
LiveData Data
Layer
In app/build.gradle file:
dependencies {
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:
$lifecycle_version"
implementation "androidx.activity:activity-ktx:$activity_version"
}
This work is licensed under the
Android Development with Kotlin Apache 2 license. 17
Using a ViewModel
Within MainActivity onCreate():
plusOneButtonA.setOnClickListener {
viewModel.incrementScore(true)
scoreViewA.text = viewModel.scoreA.toString()
}
type="com.example.kabaddikounter.ScoreViewModel" />
</data>
<ConstraintLayout ../>
</layout>
binding.viewModel = viewModel
...
<TextView
android:id="@+id/scoreViewA"
android:text="@{viewModel.scoreA.toString()}" />
...
binding.plusOneButtonA.setOnClickListener {
viewModel.incrementScore(true)
binding.scoreViewA.text = viewModel.scoreA.toString()
}
}
Observer Observer
● getValue() ● getValue()
● postValue(value: T)
● setValue(value: T)
● Create a ViewModel
to hold data separately from a UI controller
● Use ViewModel
with data binding to make a responsive UI with less code
● Use observers to automatically get updates from LiveData
This work is licensed under the
Android Development with Kotlin Apache 2 license. 40
Learn More