问题
Android Studio -> New Project -> Choice "Tabbed Activity".
After upgrading lifecycle-extensions from 2.1.0 to 2.2.0-alpha05 ViewModelProviders is deprecated. In simple cases it replaceable by "by viewModels()" for example:
plHlFrModel = ViewModelProviders.of(this).get(PlHlFrModel::class.java)
replaced by:
private val plHlFrModel by viewModels<PlHlFrModel>()
But I can't figure out how to replace this one:
pageViewModel = ViewModelProviders.of(this)
.get(PageViewModel::class.java).apply {
setIndex(arguments?.getInt(ARG_SECTION_NUMBER) ?: 1)
}
where and how to place apply{} block in a "by viewModel" form? Maybe there is another way?
回答1:
ViewModelProviers
is deperecated, we just use ViewModelProvider.
Direct access
pageViewModel = ViewModelProvider(this)
.get(PageViewModel::class.java).apply {
setIndex(arguments?.getInt(ARG_SECTION_NUMBER) ?: 1)
}
using delegate
private val pageViewModel by viewModels<PageViewModel>()
//function scope
pageViewModel.setIndex(arguments?.getInt(ARG_SECTION_NUMBER) ?: 1)
回答2:
Instead of using ViewModelProviders.of(this)
use ViewModelProvider(This)
new ViewModelProvider(this).get(Vm.class);
for java
来源:https://stackoverflow.com/questions/58146582/viewmodelproviders-is-deprecated-after-upgrading-lifecycle-extensions2-1-0-t