Kotlin中的ViewModel:未解决的参考 [英] ViewModel in Kotlin: Unresolved Reference
问题描述
我正在尝试在100%Kotlin应用中实现ViewModel.我能找到的每篇文档都说我想用它来获取ViewModel实例:
I am trying to implement ViewModel in a 100% Kotlin app. Every piece of documentation I can find says I want to use this to get the ViewModel instance:
ViewModelProviders.of(this).get(CustomViewModel::class.java)
根据文档,我应该可以使用以下命令导入该文件:
According to the docs, I should be able to import this with:
import android.arch.lifecycle.ViewModelProviders
此导入尚未解决.我在构建文件中使用了以下内容:
This import is unresolved though. I am using the following in my build file:
def androidArchVersion = '1.1.1'
implementation "android.arch.lifecycle:viewmodel:$androidArchVersion"
implementation "android.arch.lifecycle:livedata:$androidArchVersion"
annotationProcessor "android.arch.lifecycler:compiler:$androidArchVersion"
testImplementation "android.arch.core:core-testing:$androidArchVersion"
为什么我不能访问ViewModelProviders
?
推荐答案
包括以下内容作为依赖项:
Include the following as a dependency:
implementation "android.arch.lifecycle:extensions:1.1.1"
此依赖关系同时适用于ViewModel和LiveData,因此不需要您为相同的视图分别提供依赖关系;即您所指示的前两个依赖项可以由上述生命周期扩展依赖项代替.
This dependency is for both ViewModel and LiveData and thus would not require you to give separate dependencies for the same either; i.e. the first two dependencies indicated by you can be replaced by the aforementioned lifecycle extensions dependency.
这篇关于Kotlin中的ViewModel:未解决的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!