4

我正在尝试创建一个 ViewModelFactory 来创建我的 ViewModel。

工厂类是:

class GameViewModelFactory(private val application: GameApplication) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(GameViewModel::class.java)) {
            return GameViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

我也尝试过扩展,ViewModelProvider.AndroidViewModelFactory(application)但结果是一样的。

ViewModel 类的构造函数是:

class GameViewModel(private val gameApplication: GameApplication) : AndroidViewModel(gameApplication)

我在片段中完全调用它的方式如下:

val remoteViewModelFactory = GameViewModelFactory(GameApplication())
        gameViewModel = ViewModelProviders
                .of(this, remoteViewModelFactory)
                .get(GameViewModel::class.java)

问题来了,它似乎没有得到它,我认为这可能是因为Application对象。我已经尝试在我的GameApplication班级中创建一个单例,但它仍然是一样的:

Caused by: java.lang.RuntimeException: Cannot create an instance of class trate.data.viewmodel.GameViewModel
    at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:133)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:101)
    at trate.ui.game.GameFragment.onCreate(GameFragment.kt:70)

非常感谢!

编辑:如果我调试并进入 VieWModelProvider 类,我会看到它到达AndroidViewModelFactory该类并进入getcreate 方法。然后它尝试返回modelClass.getConstructor(Application.class).newInstance(mApplication),但随后抛出以下内容RuntimeException

result = {NoSuchMethodException@5072} "java.lang.NoSuchMethodException: <init> [class android.app.Application]"
 backtrace = {Object[32]@5085} 
 cause = {NoSuchMethodException@5072} "java.lang.NoSuchMethodException: <init> [class android.app.Application]"
 detailMessage = "<init> [class android.app.Application]"
 stackTrace = {StackTraceElement[0]@5087} 
 suppressedExceptions = {Collections$EmptyList@5088}  size = 0
 shadow$_klass_ = {Class@3232} "class java.lang.NoSuchMethodException"
 shadow$_monitor_ = -2097726229
4

0 回答 0