无法解析符号 ViewModel

Cannot resolve symbol ViewModel

我希望存储数据以处理屏幕方向的变化,这会导致每次方向变化时调用 onCreate 方法。因此,根据 Android 文档,建议使用 'ViewModel' 但我收到无法解析 ViewModel 的错误。

[Cannot use android:configChanges as I have a different landscape and portrait views]

代码如下:

public static class MyViewModel extends ViewModel {
    private String mUserId;
    private String mProductId;
}

嘿,你需要在构建中实现这两行 gradle:

implementation "android.arch.lifecycle:extensions:1.1.0"
implementation "android.arch.lifecycle:viewmodel:1.1.0"

我在尝试使用 Android Studio 2.3 时遇到了同样的问题。我尝试了许多 Gradle 更改等,但没有成功。我升级到新的 Studio 3.2.1 并且工作正常。不确定您使用的是哪个 Studio 版本。 我仍然需要将 lifecycle:extensions 的实现行添加到模块(不是项目)的 build.gradle 文件中:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1' <== added
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

如果没有添加实现行,将无法找到 "ViewModelProviders"。