ViewModelProvider.get 总是给出未解决的参考

ViewModelProvider.get always gives unresolved reference

我正在尝试在我的应用程序中使用 ViewModel 库,我创建了一个 class MainActivityViewModel 来扩展 ViewModel class。当尝试使用 ViewModelProvider.get(Class)MainActivity 中实例化 MainActivityViewModel class 时,get 方法总是导致未解析的引用

MainActivityViewModel class:

class MainActivityViewModel: ViewModel() {
    private lateinit var mWords: MutableLiveData<List<Word>>

    fun getWords(): LiveData<List<Word>>{
        return mWords
    }
}

MainActivity class:

class MainActivity : AppCompatActivity() {

private lateinit var mMainActivityViewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val recycler = findViewById<RecyclerView>(R.id.recycler)
    recycler.adapter = RecyclerAdapter(this)
    recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

    mMainActivityViewModel = ViewModelProvider.get(MainActivityViewModel::class.java)
}

} 我不确定我在这里做错了什么,

用于 liveData 的依赖项:

def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"
implementation 'androidx.core:core-ktx:1.3.2'
implementation "androidx.fragment:fragment-ktx:1.2.5"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

提前致谢

你需要传入上下文,让ViewModel知道什么时候可以销毁。

mMainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

您需要为视图模型提供者传递所有者 (Activity/fragment)

mMainActivityViewModel= ViewModelProvider(this).get(MainActivityViewModel::class.java)

您也可以这样声明它

import androidx.fragment.app.viewModels  //use this import

val mMainActivityViewModel: MainActivityViewModel by viewModels() // no need to initialize it again