'ViewModelProviders' is deprecated. After upgrading lifecycle-extensions:2.1.0 to 2.2.0-alpha05

十年热恋 提交于 2020-01-04 20:45:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!