'by viewModels()' Kotlin 属性委托未解析的引用

Ton*_*Joe 31 android viewmodel kotlin

我正在尝试使用 kotlin 实现视图模型。首先,我添加了所需的依赖项:

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
// Annotation processor
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0"
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个简单的视图模型:

class MyViewModel: ViewModel() {
    val greeting = "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用 kotlin 属性委托从活动访问视图模型时:

val model by viewModels<MyViewModel>()
Run Code Online (Sandbox Code Playgroud)

编译器不解析viewModels. 我不知道是什么问题。我错过了什么?

IR4*_*R42 46

添加这些依赖项:

implementation "androidx.activity:activity-ktx:$activity_version"
implementation "androidx.fragment:fragment-ktx:$fragment_version"
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到最新版本的库:

https://developer.android.com/jetpack/androidx/releases/activity

https://developer.android.com/jetpack/androidx/releases/fragment

  • 片段 ktx 应该足够了 (6认同)

Joo*_*lah 17

对我来说,上面的解决方案不起作用。

我需要导入:

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
Run Code Online (Sandbox Code Playgroud)


Pra*_*iya 6

解决了此错误,在模块级build.gradle中使用以下依赖项

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
Run Code Online (Sandbox Code Playgroud)

或者

implementation 'androidx.lifecycle:lifecycle-extensions-ktx:2.2.0'
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.3.6'
Run Code Online (Sandbox Code Playgroud)

我还添加了以下依赖项以在Kotlin中实现ViewModel

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
Run Code Online (Sandbox Code Playgroud)

我的模块级build.gradle开始如下

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这取决于您如何使用 ViewModel。如果您不使用片段,这足以解决活动的“未解析的引用:viewModels”。

// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
implementation 'androidx.activity:activity-ktx:1.6.1' 
Run Code Online (Sandbox Code Playgroud)
// is to add the dependency on Fragment
implementation 'androidx.fragment:fragment-ktx:1.2.5'
Run Code Online (Sandbox Code Playgroud)
// is to add the dependency on Activity
implementation 'androidx.activity:activity-ktx:1.1.0' 
Run Code Online (Sandbox Code Playgroud)