目录
三、ViewModel+LiveData实现Fragment通信
4.Fragment中监听LiveData数据并添加SeekBar监听
一、作用
LiveData是一个可被观察到数据容器类,它将数据包装起来,使数据成为被观察者,当数据发生变化时,观察者能够获得通知。
二、使用方法
1.定义LiveData
lateinit var liveData: MutableLiveData<Int>
2.观察LiveData数据
通过observe()方法观察LiveData数据变化,并在回调中实现数据展示
liveData.observe(this, {
findViewById<TextView>(R.id.tv).text = it.toString()
})
3.修改LiveData数据
通过setValue()或postValue()方式实现数据修改,postValue方法用在非UI线程中,setValue方法用在UI线程中
liveData.value = 0
liveData.postValue(0)
此Demo是在上一篇文章《【Jetpack系列】ViewModel(Kotlin)》中ViewModel的基础上,将接口回调方式更新并展示数据改为用LiveData实现同样的功能
完整代码
TimerWithLiveDataViewModel
class TimerWithLiveDataViewModel : ViewModel() {
var timer: Timer? = null
var currentSecond = MutableLiveData<Int>()
fun startTime() {
if (timer == null) {
timer = Timer()
currentSecond.value = 0
val timerTask = object : TimerTask() {
override fun run() {
currentSecond.postValue(currentSecond.value!! + 1)
}
}
timer!!.schedule(timerTask, 0, 1000)
}
}
}