androidkotlinviewmodel

'by viewModels()' Kotlin property delegate unresolved reference


I'm trying to implement viewmodel with kotlin. First I added the needed dependecies:

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"

Then I created a simple viewmodel:

class MyViewModel: ViewModel() {
    val greeting = "Hello World"
}

But when I tried to access the view model from the activity with kotlin property delegate:

val model by viewModels<MyViewModel>()

The compiler does not resolve viewModels. I don't know what the problem is. Did I miss something?


Solution

  • Add these dependencies:

    implementation "androidx.activity:activity-ktx:$activity_version"
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    

    You can find the latest versions of libraries here:

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

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