Savedstateviewmodelfactory is finall, cannot inherit

别说谁变了你拦得住时间么 提交于 2021-01-29 05:13:47

问题


class SettingsViewModelFactory(application: Application, owner: SavedStateRegistryOwner) : SavedStateViewModelFactory(application, owner){


    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(SettingsViewModel::class.java)){
            return SettingsViewModel() as T
        }
        throw IllegalArgumentException("Invalid ViewModel class")
    }

}

I get a red underline below SavedStateViewModelFactory saying that the type is final and cannot be inherited from. What do I do? The documentation is too vague. Also what state do I put into the return?


回答1:


If you want to create your own factory that allows for usage of SavedStateHandle constructor parameters, you would extend AbstractSavedStateViewModelFactory, not SavedStateViewModelFactory as per the explicit note on the documentation:

When providing a custom ViewModelProvider.Factory instance, you can enable usage of SavedStateHandle by extending AbstractSavedStateViewModelFactory.

However, you don't need any custom factory to support a ViewModel with a zero argument constructor - that is supported by default. You'd only need a custom factory if you need to pass custom parameters to your ViewModel. In your code's case, you can delete your custom factory entirely.



来源:https://stackoverflow.com/questions/62850680/savedstateviewmodelfactory-is-finall-cannot-inherit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!