简体   繁体   English

Android ViewModelProvider.of() 找不到符号

[英]Android ViewModelProvider.of() cannot find symbol

I tried to get my custom ViewModel 'ViewModelSavegame' with the ViewModelProvider to set a Observer.我试图让我的自定义 ViewModel 'ViewModelSavegame' 与 ViewModelProvider 一起设置一个观察者。

viewModelSavegame = ViewModelProvider.of(this).get(ViewModelSavegame.class);
        viewModelSavegame.GetSavegameName().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(String s)
            {
                TextView title = (TextView) findViewById(R.id.textViewTitel);
                title.setText(s);
            }
        });

In the Gradle build (module:app) I have dependencies在 Gradle 构建(模块:应用程序)中,我有依赖项

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata:2.2.0"
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

But ViewModelProvider.但是 ViewModelProvider。 of () create the error: of () 创建错误:

error: cannot find symbol viewModelSavegame = ViewModelProvider.of(this).get(ViewModelSavegame.class);错误:找不到符号 viewModelSavegame = ViewModelProvider.of(this).get(ViewModelSavegame.class); ^ symbol: method of(SavegameTabbedActivity) ^ 符号:(SavegameTabbedActivity) 的方法

Did I missed something maybe a dependencie?我错过了一些可能是依赖的东西吗?

将代码从 ViewModelProvider.of(this).get(ViewModelSavegame.class) 更改为 ViewModelProvider(this).get(ViewModelSavegame.class)。

Solution:解决方案:

Use
viewModelSavegame = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(ViewModelSavegame.class);

Maybe someone can provide further information, but of() seems to be replaced with getInstance().也许有人可以提供进一步的信息,但 of() 似乎被 getInstance() 取代。 I hope this is the correct way to use this in an TabbedActivity and their fragments to provide the same view model, but at least it works, without crashing the app.我希望这是在 TabbedActivity 及其片段中使用它以提供相同视图模型的正确方法,但至少它可以工作,而不会使应用程序崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM