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

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

提交回复
热议问题