无法解析符号ViewModel

时间:2018-11-27 12:37:24

标签: android android-viewmodel

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

  

[由于我的横向和纵向视图不同,因此无法使用android:configChanges]

代码如下:

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

2 个答案:

答案 0 :(得分:0)

嘿,您需要在build gradle中实现这两行:

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

答案 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”。