问题描述
我是mvvm模式的新手.我为主要活动创建了一个ViewModel.现在,我想在主活动中获取ViewModel的实例.
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.
Stackoverflow上的大多数教程和解答建议使用ViewModelProviders.of(...
,但已弃用.
Most Tutorials and answers here on Stackoverflow suggest using ViewModelProviders.of(...
, but this is depreceated.
因此,根据关于stackoverflow的以下问题: ViewModelProviders在1.1中已弃用.0 在onCreate中的主要活动,我执行以下操作(并且我发誓我已经运行了它):mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
So according to this question on stackoverflow: ViewModelProviders is deprecated in 1.1.0 main activity in onCreate, I do the following (and I could swear I already had it running): mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
但是,我收到一个错误消息,告诉我没有找到合适的构造函数.
However, I am getting an error telling me, that no suitable constructor has been found.
error: no suitable constructor found for ViewModelProvider(MainActivity)
或者,要明确指出,MainActivity应该是ViewModelStoreOwner,我创建了一个变量ViewModelStoreOwner vmso = this;
并将该变量放入构造函数中,如下所示:mainActivityViewModel = new ViewModelProvider(vmso).get(MainActivityViewModel.class);
Alternatively to make absolutely clear, that the MainActivity shall be the ViewModelStoreOwner, I created a variableViewModelStoreOwner vmso = this;
and put that variable into the constructor like so:mainActivityViewModel = new ViewModelProvider(vmso).get(MainActivityViewModel.class);
推荐答案
目前,对我而言唯一有效的方法是使用:MainActivityViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MainActivityViewModel.class);
For now, the only thing working for me was to use:MainActivityViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MainActivityViewModel.class);
但是,我仍然感谢任何建议,如何使用new ViewModelProvider(this).get(MainActivityViewModel.class);
However, I am still thankful for any advice, how this can be done different using new ViewModelProvider(this).get(MainActivityViewModel.class);
这篇关于2020年如何在活动中获取ViewModel实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!