This question already has answers here:
ViewModel in Kotlin: Unresolved Reference

(7个答案)


去年关闭。




我刚启动一个Android应用程序,并且想使用ViewModel。我查看了文档,并放入了Lifecycle的所有依赖项,但是当我尝试实例化类似于此 View MyViewModel by viewModels()的 View 模型时,出现此错误“ Unresolved 引用:viewModels()”。

这些是依赖项:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0"

    implementation "android.arch.lifecycle:extensions:1.1.1"
    kapt "android.arch.lifecycle:compiler:1.1.1"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"
    testImplementation "androidx.arch.core:core-testing:$arch_version"

}

最佳答案

将此添加到您的依赖项中,

implementation "android.arch.lifecycle:extensions:1.1.1"

然后,在build.gradle中添加apply plugin: 'kotlin-kapt'
然后加,
kapt "android.arch.lifecycle:compiler:1.1.1"

annotationProcessor替换其他kapt
查看它是否有效,如果无效,请转到

10-08 14:14