一、导入依赖
新建 LiveDataDemo
工程,在 build.gradle(Module:app)
中参考 Lifecycle 声明依赖项 导入依赖。
dependencies {
def lifecycle_version = "2.2.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
...
}
二、搭建布局
在 activity_main.xml
搭建简单布局(省略属性),如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
tools:context=".MainActivity">
<TextView
android:id="@+id/tvVote" />
<ImageButton
android:id="@+id/imgBtnUpvote" />
<ImageButton
android:id="@+id/imgBtnDownvote" />
</androidx.constraintlayout.widget.ConstraintLayout>
包含三个控件:
tvVote
- TextView,显示点赞数;imgBtnUpvote
- ImageButton,点赞的按钮;imgBtnDownvote
- ImageButton,点踩的按钮。
注意:在 ImageButton
使用 res/drawble
添加的 Vector Asset
作为 app:srcCompat
时,需要在 build.gradle(Module:app)
中添加:
android {
defaultConfig {
...
vectorDrawables.useSupportLibrary = true
}
}
整体布局如图:
三、创建 LiveData 对象
在 com.example.viewmodeldemo
目录下新建 VoteViewModel
类继承自 ViewModel()
,参考 官方 LiveData 概述,定义一个 MutableLiveData
类型的属性,并定义两个方法 upVote()
和 downVote()
,如下:
class VoteViewModel : ViewModel() {
val vote: MutableLiveData<Int> by lazy {
MutableLiveData<Int>(0)
}
fun upVote() {
vote.value = vote.value?.plus(1)
}
fun downVote() {
vote.value = vote.value?.minus(1)
}
}
四、观察 LiveData 对象
参考 官方 LiveData 概述,在 MainActivity
类中,使用 Kotlin by viewModels()
属性委托来声明一个 VoteViewModel
的实例:
private val voteViewModel: VoteViewModel by viewModels()
使用该属性委托需要在 build.gradle(Module:app)
添加 androidx.activity
依赖:
dependencies {
...
def activity_version = "1.1.0"
// androidx.activity
implementation "androidx.activity:activity-ktx:$activity_version"
...
}
此时 viewModels()
仍报错:
Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6.
Please specify proper '-jvm-target' option
需要在 build.gradle(Module:app)
里加入:
android {
...
// Java
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// For Kotlin projects
kotlinOptions {
jvmTarget = "1.8"
}
}
在 MainActivity.onCreate()
中创建观察者来更新 TextView
控件,并监听两个按钮的点击事件,分别调用 VoteViewModel
的 upVote()
和 downVote()
方法:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
voteViewModel.vote.observe(this, Observer<Int> { newVote ->
tvVote.text = newVote.toString()
})
imgBtnUpvote.setOnClickListener {
voteViewModel.upVote()
}
imgBtnDownvote.setOnClickListener {
voteViewModel.downVote()
}
}
五、Demo 效果
效果如下: