android - 如何为 AndroidViewModel 创建 View 模型工厂?

标签 android kotlin android-architecture-components android-jetpack android-viewmodel

我需要在创建 View 模型时传递值(userData),所以我需要创建一个 View 模型工厂

这是我的viewModel,我需要applicationuserData初始化 ScoreViewModel

class ScoreViewModel(application: Application, userData: UserKM) : AndroidViewModel(application) {



}

但现在我很困惑如何通过application当我创建 viewModel 工厂时
class ScoreViewModelFactory(private val userData: UserKM) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ScoreViewModel::class.java)) {

            return ScoreViewModel(userData = userData,application = ?????? ) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }

}

我应该怎么办 ?

最佳答案

你可以有这样的东西:

class Factory(val app: Application) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(NewsViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return NewsViewModel(app) as T
            }
            throw IllegalArgumentException("Unable to construct viewmodel")
        }
    }

在您的 Activity 或 fragment 中,您有:
/**
     * One way to delay creation of the viewModel until an appropriate lifecycle method is to use
     * lazy. This requires that viewModel not be referenced before onActivityCreated, which we
     * do in this Fragment.
     */
    private val viewModel: NewsViewModel by lazy {
        val activity = requireNotNull(this.activity) {
            "You can only access the viewModel after onActivityCreated()"
        }
        ViewModelProviders.of(this, NewsViewModel.Factory(activity.application))
            .get(NewsViewModel::class.java)
    }

在这里,您的 viewModel 可能如下所示:
class NewsViewModel(application: Application) : AndroidViewModel(application)

有关更多详细信息,您可以查看:https://github.com/Ali-Rezaei/News-Cache/blob/master/app/src/main/java/com/sample/android/news/viewmodels/NewsViewModel.kt

关于android - 如何为 AndroidViewModel 创建 View 模型工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786299/

相关文章:

Android 架构导航 - onSupportNavigateUp()

Android 在调用 ft.replace 时为同一 fragment 返回不同的 ViewModel 实例

php - Android 应用程序在 Http 请求连接到在线数据库时崩溃

android - 在 Android : how to use gluUnProject? 上打开 GL ES

android - 使用 android simpleCursorAdapter 的多个 ListViews

kotlin - kotlin 使用谁的 Collection 接口(interface)实现?

java - kotlin 内部类的目的是什么?

android - 改造协程 livedata 仅第一次调用

android - 错误: String types not allowed (at 'ga_logLevel' with value 'verbose' )

kotlin - Intellij中的Kotlin构造函数引用