欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android: ViewModel> has no zero argument constructor

程序员文章站 2022-03-26 15:02:37
viewModel = ViewModelProvider( this, ViewModelProvider.AndroidViewModelFactory.getInstance(application) ).get(PDFBookDocumentViewModel::class.java)使用上述方法加载viewModel报上述错误。如果您想为ViewModel类提供一个非零参数的构造函数,则可能必须创......
        viewModel = ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(PDFBookDocumentViewModel::class.java)

使用上述方法加载viewModel报上述错误。如果您想为ViewModel类提供一个非零参数的构造函数,则可能必须创建一个自定义ViewModelFactory类来初始化ViewModel实例,该实例将实现ViewModelProvider.Factory接口

解决方案:https://*.com/questions/44194579/android-viewmodel-has-no-zero-argument-constructor

 

1. 创建一个自定义ViewModelFactory类:

class ViewModelFactory constructor(
        private val sharePref: SharedPreferences,
        private val topRepository: ITopRepository,
) : ViewModelProvider.NewInstanceFactory() {

    override fun <T : ViewModel> create(modelClass: Class<T>) =
            with(modelClass) {
                when {
                    isAssignableFrom(PDFBookDocumentViewModel::class.java) ->
                        PDFBookDocumentViewModel(PDFBookDocumentUseCase(topRepository))
                    else ->
                        throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
                }
            } as T
    
    companion object {
        @Volatile
        var INSTANCE: ViewModelFactory? = null

        fun getInstance(
                sharePref: SharedPreferences,
                iTopRepository: ITopRepository,
        ): ViewModelFactory {
            if (INSTANCE == null) {
                synchronized(ViewModelFactory::class) {
                    if (INSTANCE == null) {
                        INSTANCE =
                                ViewModelFactory(
                                        sharePref,
                                        iTopRepository
                                )
                        RetrofitManager.sharedPreferences = sharePref
                    }
                }
            }
            return INSTANCE!!
        }
    }
}

 

2: 获取用于在Activity中创建ViewMode的Factory:

/**
 *
 * 获取用于在Activity中创建ViewMode的Factory
 *
 * @return ViewModelFactory
 */
fun Activity.getViewModelFactory(): ViewModelFactory {
    val sharePref = SharedPreferences(applicationContext)
    val topRepository = (applicationContext as MyApplication).topRepository
    return ViewModelFactory.getInstance(
        sharePref,
        topRepository,
    )
}

 

3: Activity中绑定viewModel的代码用如下替换:

 viewModel = viewModels<PDFBookDocumentViewModel> { getViewModelFactory() }.value

 

 

 

本文地址:https://blog.csdn.net/Crystal_xing/article/details/108868026

相关标签: android bug