java.lang.ClassCastException: com.eng.bt_eng_mobility.viewmodel.HomeViewModelFactory 无法转换为 androidx.lifecycle.ViewModel

java.lang.ClassCastException: com.eng.bt_eng_mobility.viewmodel.HomeViewModelFactory cannot be cast to androidx.lifecycle.ViewModel

我收到这个错误。我在同一个 ViewModel class 文件中创建了 ViewModelFactory class。 当我尝试初始化视图模型时出现此错误。

//Code written in fragment class in onCreateView after binding code//
homeViewModelFactory = HomeViewModelFactory((requireActivity().application as Application).repository)
        homeViewModel = ViewModelProvider(this, homeViewModelFactory)
                .get(HomeViewModel::class.java)


//Viewmodelfactoryclass//
class HomeViewModelFactory(private val homeRepository: HomeRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
            return HomeViewModelFactory(homeRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


ViewModelProvider.Factory 的工作是创建 ViewModel class 的实例。目前,您所做的只是 return 创建工厂的新实例。

相反,您的 return 语句可能应该是这样的:

return HomeViewModel(homeRepository) as T

This article 更详细地介绍了 ViewModel 的基础知识。