ViewModel
添加依赖
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
比较好的编程规范是给每一个Activity和Fragment都创建一个对应的ViewModel
import androidx.lifecycle.ViewModel
class MainViewModel(countReserved: Int) : ViewModel() {
var counter = countReserved
}
Lifecycles组件:感知Activity生命周期
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class MainViewModelFactory(private val countReserved: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MainViewModel(countReserved) as T
}
}
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx