ViewModel
class MyViewModel : ViewModel() {
var number = 0
}
MainActivity
class MainActivity : AppCompatActivity() {
private val myViewModel by viewModels<MyViewModel>()
var mBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
mBinding!!.tv.text = myViewModel.number.toString()
mBinding!!.btn.setOnClickListener {
myViewModel.number++
mBinding!!.tv.text = myViewModel.number.toString()
}
}
}
页面重建时数据不会丢失
ViewModelSavedState
const val NUMBER_KEY = "number_key"
class MyViewModel(private val state:SavedStateHandle) : ViewModel() {
var number:Int
get() {
return state.get<Int>(NUMBER_KEY)?:0
}
set(value) {
state[NUMBER_KEY] = value
}
}
MainActivity
class MainActivity : AppCompatActivity() {
private val myViewModel by lazy {
ViewModelProvider(this, SavedStateViewModelFactory(application, this)).get(MyViewModel::class.java)
}
var mBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
mBinding!!.tv.text = myViewModel.number.toString()
mBinding!!.btn.setOnClickListener {
myViewModel.number++
mBinding!!.tv.text = myViewModel.number.toString()
}
}
}
再次运行程序,数据就不会丢失了。
需要注意的是,这里的数据也不是永久保存的,当手机重启或者用户手动杀掉进程后,数据仍然会丢失。