这是我的 ViewModel 类:
class ViewModel(private val savedStateHandle: SavedStateHandle, private val dataSource: DataSource) : ViewModel()
这是我的 ViewModelProvider.Factory 类:
class ViewModelProviderFactory(
private val savedStateHandle: SavedStateHandle,
private val dataSource: DataSource
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ViewModel(savedStateHandle, dataSource) as T
}
}
在我的活动课上,我有:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: ViewModel by viewModels()
...
}
如何获取 SavedStateHandle 传递给 ViewModelProvider.Factory 以便我可以创建我的 ViewModel?
您可以使用
ViewModelProvider.Factory
的其他创建方法:
class ViewModelProviderFactory(
private val dataSource: DataSource
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
return ViewModel(extras.createSavedStateHandle(), dataSource) as T
}
}
并且在通过
by viewModels()
语法初始化ViewModel时,不要忘记传递工厂参数:
private val viewModel: ViewModel by viewModels(factory = ViewModelProviderFactory(dataSource))
还有另一种方法可以避免创建 ViewModelProvider.Factory 的麻烦,即使用 hilt,您可以参考此链接尝试 hilt:https://dagger.dev/hilt/view-model