ViewModel in Kotlin: Unresolved Reference

故事扮演 提交于 2020-05-23 07:46:10

问题


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"

Why can't I access ViewModelProviders?


回答1:


Include the following as a dependency:

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

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.




回答2:


In addition to what Sup suggested, you'll have to correct lifecycler:compiler to lifecycle:compiler - the Gradle sync shouldn't even complete successfully with this typo.

Secondly, the standard android annotation processing ("annotationProcessor") doesn't really work with Kotlin. Instead, use Kotlin's kapt.

At the top of your build.gradle file, add the following:

apply plugin: 'kotlin-kapt'.

And in your dependencies section, replace occurences of annotationProcessor (like the above one) with kapt, e.g.

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




回答3:


If the above "adding/updating dependecies" did not resolve your issue then try to restart your android studio. It´s just to root, I do not see any major issue with it. Hope it helps.




回答4:


I faced this kind of problem in AndroidStudio 3.0.1 and solved by adding following dependencies in the proper build.gradle:

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

version code may be different as AndroidStudio tells you if it differs.




回答5:


This can also be resolved by targeting minSdkVersion to 21.

If you have minSdkVersion 21 or higher, you won't need implementation "android.arch.lifecycle:extensions:1.1.1".



来源:https://stackoverflow.com/questions/49934658/viewmodel-in-kotlin-unresolved-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!