问题
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 ofSavedStateHandle
by extendingAbstractSavedStateViewModelFactory
.
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