[英]Android kotlin passing dynamic arguments/parameters to ViewModel with ViewModelFactory
To transfer additional arguments/parameters for ViewModel we used ViewModelFactory.为了为 ViewModel 传输额外的参数/参数,我们使用了 ViewModelFactory。 For example例如
ExtraParamsViewModelFactory(this.requireActivity().application, "some string value")
But when the ViewModel is created, I can't change the arguments/parameters dynamically但是当创建 ViewModel 时,我无法动态更改参数/参数
val myViewModel = ViewModelProvider(this, ExtraParamsViewModelFactory(this.requireActivity().application, "some string value")).get(SomeViewModel::class.java)
"some string value" becomes harcoded in fragment/activity class. “一些字符串值”在片段/活动 class 中被硬编码。 In "some string value" I need to pass a date that is always different to ViewModel.在“一些字符串值”中,我需要传递一个始终与 ViewModel 不同的日期。 In the fragment, the user selected a date, clicked on the button and this date as a arguments/parameters pass to ViewModel.在片段中,用户选择了一个日期,点击了按钮,这个日期作为参数/参数传递给 ViewModel。 Not suitable for this ViewModelFactory?不适合这个 ViewModelFactory?
No need to pass arguments in ViewModel constructor.无需在 ViewModel 构造函数中传递 arguments。 all what you need is a is a setter & warrper class depending on your use.您需要的只是一个 setter & warrper class,具体取决于您的用途。
I guess your ViewModel will have some thing like this我猜你的 ViewModel 会有这样的东西
data class CustomWrapper<T>(var value:T)
class VM : ViewModel(){
private val stringValue = CustomWrapper<String>("")
fun setNewStringValue(value:String){
stringValue.value = value
//TODO:: update stuff related to `stringValue`
}
}
then in your Activity/Fragment..simply call it..like this然后在你的 Activity/Fragment 中..只需调用它..像这样
vm.setNewStringValue("new value")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.