ViewModel:未解决的引用

ViewModel: Unresolved reference

我想在我的应用程序中实现 ViewModel,但我无法导入 viewModels()activityViewModels()。尝试按照教程进行操作,但它对我来说仍然是未解决的参考。

private val userViewModel: ProfileFlowFragment.UserViewModel by viewModels()

进口:

implementation "androidx.fragment:fragment-ktx"
implementation "androidx.activity:activity-ktx"

// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0"

您是否在 implementation "androidx.fragment:fragment-ktx" 中指定了版本? 无论如何,我的 Gradle 文件中有这些依赖项,一切都很好。

 implementation "androidx.core:core-ktx:$corektxVersion"
 implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_stdlibVersion"

同时添加

apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

下面是最新的稳定版本,应该可以。

 def activity_version = "1.2.0"
 def fragment_version = "1.3.0"
 implementation "androidx.activity:activity-ktx:$activity_version"
 implementation "androidx.fragment:fragment-ktx:$fragment_version"