简体   繁体   English

如何在活动和片段中使用相同的 ViewModel 实例?

[英]How to use same instance of ViewModel in activity as well as fragment?

I have created an instance of ViewModel in MainActivity and setup an observer.我在MainActivity中创建了一个 ViewModel 实例并设置了一个观察者。 I want the observed data into one of the fragments of MainActivity's ViewPager.我希望将观察到的数据放入 MainActivity 的 ViewPager 的片段之一。 How can I get the required LiveData into the fragment .如何将所需的LiveData放入片段中。

Using AndroidX extension delegate使用 AndroidX 扩展委托

In the MainActivity:在 MainActivity 中:

private val activityViewModel: SomeViewModel by viewModels()

In the Fragement在片段中

private val activityViewModel: SomeViewModel by activityViewModels()

With ViewModelFactory, put the ViewModelFactory intance into closure使用 ViewModelFactory,将 ViewModelFactory 实例关闭

private val activityViewModel: SomeViewModel by viewModels{ viewModelFactory }
private val activityViewModel: SomeViewModel by activityViewModels{ viewModelFactory}

you can use shared ViewModel Shared ViewModel between activity and fragments您可以在活动和片段之间使用共享视图模型共享视图模型

for this you can define an object from activity's viewModel in your fragment with activity as viewModel's owner and apply changes on that's variables.为此,您可以从片段中的活动视图模型中定义 object,活动作为视图模型的所有者,并对其变量应用更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在带有参数的 Activity 中定义的 Fragment 中获取相同的 ViewModel 实例 - Get the same instance of ViewModel in Fragment which is defined in Activity with parameter 如何使用与Activity相同的Fragment? - How to use Fragment same as an Activity? 如何在片段和对话框片段的 ViewModel 中使用相同的 mutableLiveData - how to use the same mutableLiveData in ViewModel from fragment and dialog fragment 如何为父片段和子片段提供相同的 ViewModel 实例 - How to give same instance of ViewModel to both the Parent and Child fragment 如何在片段中使用 ViewModel? - How to use ViewModel in a fragment? 如何在每个Fragment中具有单独的ViewModel实例以及如何在Viewmodel之间共享数据 - How to have separate instance of ViewModel in each Fragment and have shared data as well between Viewmodels 如何在同一活动的片段中使用不同的onKeyDown - How to use different onKeyDown in fragment of a same activity ViewModel在Activity中设置数据并在Fragment中使用 - ViewModel set data in Activity and use in Fragment 使用相同的活动实例 - Use same instance of Activity 如何使用后台活动的相同实例? - How to use same instance of an Activity which is in background?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM