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

后端 未结 9 1527
野的像风
野的像风 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:40

    Get ViewModel In New Way

    MainActivityViewModel mainActivityViewModel;
        mainActivityViewModel= new ViewModelProvider(this).get(MainActivityViewModel.class);
    
    0 讨论(0)
  • 2021-02-13 04:44

    Use val viewModel by viewModels<TheViewModel>() in Activities and val viewModel by activityViewModels<TheViewModel>() in fragment to obtain the same viewmodel from the activity (so sharing the viewmodel).

    This is part of androidx now

    0 讨论(0)
  • 2021-02-13 04:44

    ViewModel viewModel = ViewModelProviders.of(this).get(ViewModel.class);

    Android Support library version is depreciated. So you need to make sure that you import Androidx. And you need to implement androidx dependency in Gradle file.

    It is not advised to create a new ViewModel object with "new" keyword.

    0 讨论(0)
  • 2021-02-13 04:44

    Duplicate question and already answered here

    Simply replace:

    This:

    boardViewModel = ViewModelProviders.of(this).get(BoardViewModel::class.java)
    

    With this:

    boardViewModel = ViewModelProvider(this).get(BoardViewModel::class.java)
    
    0 讨论(0)
  • 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 <T : ViewModel?> create(@NonNull modelClass: Class<T>): T {
                return  MainViewModel(_application) as T
        }
    }
    

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

    0 讨论(0)
  • 2021-02-13 04:50

    I had similar problems and in the end found out I missed off the "extends ViewModel" within the class definition, so it should look like this:

    public class ViewModelClass extends ViewModel
    {
        // Tracks the score for Team A
        public int scoreTeamA = 0;
    
        // Tracks the score for Team B
        public int scoreTeamB = 0;
    }
    
    0 讨论(0)
提交回复
热议问题