How to get an Instance of ViewModel in activity in 2020/21?

后端 未结 9 1529
野的像风
野的像风 2021-02-13 04:27

I am new to the mvvm pattern. I created a ViewModel for the main activity. Now I want to get an instance of the ViewModel in the main activity.

Most Tutorials and answe

9条回答
  •  梦如初夏
    2021-02-13 04:48

    You can use a ViewModelFactory:

    val viewModelFactory = VMFactory(requireActivity().application)
    viewModel= ViewModelProvider(requireActivity(),viewModelFactory).get(MainViewModel::class.java)
    

    VMFactory code:

    class VMFactory(application: Application) : ViewModelProvider.NewInstanceFactory() {
    
        val _application: Application=application
    
        @NonNull
        override fun  create(@NonNull modelClass: Class): T {
                return  MainViewModel(_application) as T
        }
    }
    

    Please note that here my MainViewModel extends AndroidViewModel and hence requires application as the input parameter.

提交回复
热议问题