Kotling :: Android :: java.lang.ClassCastException:java.lang.Class无法转换为androidx.lifecycle.ViewModel

时间:2019-06-12 16:41:47

标签: android mvvm kotlin dagger-2

下面代码的第一行出现异常

viewModel.homeLiveData.observe(this, Observer { list ->

        list?.let {
            mList.addAll(list)
            adapter.notifyDataSetChanged()
        }
    })
  

java.lang.ClassCastException:无法将java.lang.Class强制转换为androidx.lifecycle.ViewModel

整个代码在下面

演员表出了什么问题?创建ViewModel有什么问题吗?

我的BaseActivity

  abstract class BaseActivity<V : ViewModel> : DaggerAppCompatActivity(), HasSupportFragmentInjector {

    @Inject
    lateinit var fragmentAndroidInjector: DispatchingAndroidInjector<Fragment>

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    @LayoutRes
    abstract fun layoutRes(): Int

    protected lateinit var viewModel : V

    protected abstract fun getViewModel() : Class<V>

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home)
            onBackPressed()

        return super.onOptionsItemSelected(item)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(layoutRes())
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModel())
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentAndroidInjector
}

然后我的活动

class MainActivity : BaseActivity<MainViewModel>() {


override fun layoutRes(): Int = R.layout.activity_main

override fun getViewModel(): Class<MainViewModel> = MainViewModel::class.java

private val mList = mutableListOf<Any>()

private lateinit var adapter: DataAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

   // setSupportActionBar(toolbar)

    recyclerView.apply {
        layoutManager = GridLayoutManager(applicationContext, 2)
        adapter = DataAdapter(context, mList)

    }

    viewModel.homeLiveData.observe(this, Observer { list ->

        list?.let {
            mList.addAll(list)
            adapter.notifyDataSetChanged()
        }
    })

    viewModel.getHomeItems()


}

这是我的ViewModel

class MainViewModel @Inject constructor() : ViewModel() {


val homeLiveData: MutableLiveData<List<HomeScreenModel>> = MutableLiveData()


fun getHomeItems() {

    Handler().post {

        val homeModleList = listOf(
            HomeScreenModel(R.drawable.ic_launcher_background, MyApplication.instance.getString(R.string.settings))
        )

        homeLiveData.setValue(homeModleList)
    }
}

}

1 个答案:

答案 0 :(得分:0)

我认为,您尝试在viewModel中访问的viewModel.homeLiveData属性被getViewModel()中声明的BaseActivity抽象函数所遮盖。这是因为Kotlin认为getXyZ()是字段xyZ的吸气剂,因此,当您访问viewModel时,编译器认为您要调用getViewModel,其类型是Class<V>。我建议重命名函数或属性,然后它应该可以工作。