android - 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) 的方法
我错过了一些可能是依赖的东西吗?
解决方案
解决方案:
利用
viewModelSavegame = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(ViewModelSavegame.class);
也许有人可以提供更多信息,但 of() 似乎被 getInstance() 取代。我希望这是在 TabbedActivity 及其片段中使用它以提供相同视图模型的正确方法,但至少它可以工作,而不会导致应用程序崩溃。
推荐阅读
- javascript - 点击方法没有响应 Jamboard
- android - 我怎样才能避免 java.io.StreamCorruptedException:无效的流标头:00000000
- python - Kivy - 无法重新聚焦输入字段?
- java - th:文本无法正确显示
- jupyter-notebook - 为什么必须在 Jupyter notebook 中重新运行之前的代码框?
- airflow - 气流传感器中的“重新安排”模式如何工作?
- javascript - 使用带有画布的全屏 API
- coldfusion - 在 API 中为我们保护 ColdFusion CFAdmin 密码
- javascript - 我有一个 javascript 数组,想按名称调用图像
- python - 我想在重启后使用 Pexpect-pxssh 重新登录到远程主机。重启设备大约需要 15 分钟才能恢复在线