[英]How do I set first values to the viewmodel of EditActivity from getIntent
I have a recyclerview containing rows of info about fruits like name, color, weight, description, matching food...我有一个 recyclerview 包含有关水果的信息行,如名称、颜色、重量、描述、匹配的食物......
if i click a button it should load those row values into the intent and take me to startActivityForResult: EditActivity.如果我单击一个按钮,它应该将这些行值加载到 Intent 中,并将我带到 startActivityForResult: EditActivity。
Well the reason for the viewmodel is to prevent rotation from resetting the values back to the ones from getIntent.好吧,视图模型的原因是防止旋转将值重置回 getIntent 中的值。 The values only get updated to sql in the mainactivity onreturnresultsomething... method.
值仅在 mainactivity onreturnresultsomething... 方法中更新为 sql。
if i do '''mviewmodel.name = intent.getStringExtra(name,""):''' in mainactivity oncreate, that would just overrite it on rotation just as if there was no viewmodel at all.如果我在 mainactivity oncreate 中执行 '''mviewmodel.name = intent.getStringExtra(name,""):''',那只会在旋转时覆盖它,就好像根本没有视图模型一样。
I'm thinking of using sharedpreferences, but there's a better way, and androidviewmodel is an antipattern.我正在考虑使用共享首选项,但有更好的方法,而 androidviewmodel 是一种反模式。
so from getintent how do i add default values to viewmodel in editactivity and that it doesnt get set back to that on rotation?因此,从 getintent 开始,我如何将默认值添加到编辑活动中的视图模型,并且它不会在旋转时设置回原来的值?
thanks all!谢谢大家!
put your values on [SavedStateHandle]: https://developer.android.com/reference/androidx/lifecycle/SavedStateHandle将您的值放在 [SavedStateHandle] 上: https : //developer.android.com/reference/androidx/lifecycle/SavedStateHandle
mviewmodel.savedStateHandle.set("name",name)
before you set the value, check if it is null or not, something like:在设置值之前,请检查它是否为空,例如:
if(mviewmodel.savedStateHandle.get("name) == null){
mviewmodel.savedStateHandle.set("name",name)
}
you can check it from here: https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate您可以从这里查看: https : //developer.android.com/topic/libraries/architecture/viewmodel-savedstate
If you are using the current by viewModels
or the underlying ViewModelProvider
pattern your ViewModel will not be recreated, so you could add it as a constructor parameter.如果您使用当前的
by viewModels
或底层的ViewModelProvider
模式,您的 ViewModel 将不会被重新创建,因此您可以将其添加为构造函数参数。
Check out ViewModelProvider.Factory for how to do that.查看ViewModelProvider.Factory了解如何做到这一点。 Additionally if you plan on using Dagger, but you still have parameters, that you'd like to pass in manually you can check out this library: https://github.com/halcyonmobile/ViewModelFactoryGenerator
此外,如果您打算使用 Dagger,但仍有参数,您想手动传入,您可以查看此库: https : //github.com/halcyonmobile/ViewModelFactoryGenerator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.