Search code examples
androidkotlinmvvmviewmodel

Unresolved reference: viewModels


I'm trying to make a ViewModel and I have a problem with Unresolved reference: viewModels

this is an implementation of ViewModel

    private val mainVm by viewModels<MainViewModel>()

MainViewModel.kt

package com.example.aplikacjazporadnika

import androidx.lifecycle.ViewModel

class MainViewModel: ViewModel() {
    var clicker: Int = 0
}

build.gradle (Module :app)


dependencies {

    def activity_version = "1.7.2"
    // Kotlin
    implementation "androidx.activity:activity-ktx:$activity_version"

    def fragment_version = "1.6.1"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"

    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}```




I tried to add various implementations that I found in other sites but none of there actually worked

Solution

  • try manualy placing the import

    for an activity:

    import androidx.activity.viewModels
    

    for a fragment:

    import androidx.fragment.app.viewModels
    

    your dependencies seem to contain both, however if those imports still appear highlighted in red, try just clearing the caches (file -> invalidate caches)