ViewModel for Fragment instead accessing Activity ViewModel?

后端 未结 4 1980
醉话见心
醉话见心 2021-01-30 05:35

The problem is quite straightforward. The question is in context of using ViewModels, LiveData and other related Lifecycle aware arch approaches.
I have an Activity with Na

4条回答
  •  悲&欢浪女
    2021-01-30 06:16

    This is updated version of answer given by Jeel Vankhede. And also Kotlin implementation of the same.

    Since ViewModelProviders is deprecated now we have to use ViewModelProvider.

    Here is how you do it in Activity:

    ViewModelProvider(this).get(MyActivityViewModel::class.java)
    

    Here is how you do in Fragment:

    ViewModelProvider(requireActivity()).get(MyActivityViewModel::class.java)
    

提交回复
热议问题