首页 > 解决方案 > Android ViewModelProvider.of() 找不到符号

问题描述

我试图让我的自定义 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);
            }
        });

在 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'

但是 ViewModelProvider。of () 创建错误:

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

我错过了一些可能是依赖的东西吗?

标签: androidandroid-studioviewmodel

解决方案


解决方案:

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

也许有人可以提供更多信息,但 of() 似乎被 getInstance() 取代。我希望这是在 TabbedActivity 及其片段中使用它以提供相同视图模型的正确方法,但至少它可以工作,而不会导致应用程序崩溃。


推荐阅读