ViewModelProviders.of(FragmentActivity).get(ViewModel::class.java) 在 get() 调用中要求 activity 而不是 viewmodel

ViewModelProviders.of(FragmentActivity).get(ViewModel::class.java) asking for activity instead of viewmodel in get() call

ViewModelProviders.of(this).get() 由于不可预见的原因而失败 这是在我的主要 activity 中调用的,它继承自 FragmentActivity。我实际上在 .get() 调用中遇到错误。该错误表明它期望 activity 而不是违反文档的 ViewModel。我已经清除并使缓存失效。我的猜测是我有一个错误的导入或旧库版本不知何故

import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.apsoftware.urbandictionary.R

class DefinitionActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPostListBinding
    private lateinit var viewModel: DefinitionActivity


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.postList.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        viewModel = ViewModelProviders.of(this).get(DefinitionViewModel::class.java)
        binding.viewModel = viewModel
    } }

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.core:core-ktx:1.1.0-alpha04'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation "com.squareup.okhttp3:okhttp:3.12.0"
implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0"
implementation 'com.squareup.retrofit2:converter-moshi:2.5.0'
implementation 'com.squareup.moshi:moshi:1.6.0'
kapt 'com.android.databinding:compiler:3.1.4'
implementation "com.google.dagger:dagger:2.20"
kapt "com.google.dagger:dagger-compiler:2.11"
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
compileOnly "org.glassfish:javax.annotation:3.1.1"
implementation "io.reactivex.rxjava2:rxjava:2.2.2"
implementation "io.reactivex.rxjava2:rxandroid:2.0.2"
implementation "android.arch.lifecycle:extensions:1.1.1"

您已声明

private lateinit var viewModel: DefinitionActivity

viewModelDefinitionActivity 的实例。它应该是 DefinitionViewModel 以匹配您传递给 get().

的内容

改变

 private lateinit var viewModel: DefinitionActivity

 private lateinit var viewModel: DefinitionViewModel