大家下午好,我有一个问题,我想知道是什么原因造成的
我的MainActivity.kt
package com.example.albumapp.ui
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.albumapp.R
import com.example.albumapp.data.PostModel
import com.example.albumapp.viewmodel.HomeViewModel
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var adapter: HomeAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
**var vm = ViewModelProvider(this)[HomeViewModel::class.java]**
initAdapter()
vm.fetchAllPosts()
vm.postModelListLiveData?.observe(this, Observer {
if (it!=null){
rv_home.visibility = View.VISIBLE
adapter.setData(it as ArrayList<PostModel>)
}else{
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
}
progress_home.visibility = View.GONE
})
}
private fun initAdapter() {
adapter = HomeAdapter(this)
rv_home.layoutManager = LinearLayoutManager(this)
rv_home.adapter = adapter
}
}
ViewModel.kt
class HomeViewModel {
private var homeRepository:HomeRepository?=null
var postModelListLiveData : LiveData<List<PostModel>>?=null
init {
homeRepository = HomeRepository()
postModelListLiveData = MutableLiveData()
}
fun fetchAllPosts(){
postModelListLiveData = homeRepository?.fetchAllPosts()
}
}
我想知道为什么会导致类型不匹配,以及如何修复这种类型不匹配? (有两颗星的线是引起问题的地方)
最佳答案
你的 HomeViewModel 应该像这样扩展 ViewModel
class HomeViewModel : ViewModel() {
}
那就试试这个
var homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
关于android - 类型不匹配 : inferred type is HomeViewModel! 但 ViewModel!预计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68117592/