简体   繁体   English

如何在 Android 中存储和更新活动和片段之间的公共(临时)数据?

[英]How can I store and update a common (temporary) data between activities and fragments in Android?

i have an application with multiple fragments and activities.我有一个包含多个片段和活动的应用程序。 I'm wondering if I can create a container class between fragments.我想知道是否可以在片段之间创建一个容器 class。 (I want to save with set and pull with get) (我想用set保存,用get拉)

For example, I will save the gender information of the user in the FragmentA class, and then I will use this information when I switch to FragmentB.比如我会在FragmentA class中保存用户的性别信息,然后切换到FragmentB时会用到这个信息。 In the same way;以同样的方式; I will get the user's age, height, weight in FragmentC class. and then I will access this information in the FragmentE (Final) class and save it to the Room database.我将在 FragmentC class 中获取用户的年龄、身高、体重,然后我将在 FragmentE (Final) class 中访问这些信息并将其保存到 Room 数据库中。 How can I do this?我怎样才能做到这一点? Could you please give an example in Java?你能在Java中举个例子吗?

Note: I'm using Shared Preferencens but I want to look for a different method as I don't know if it works asynchronously or synchronously.注意:我正在使用 Shared Preferencens,但我想寻找一种不同的方法,因为我不知道它是异步工作还是同步工作。 For example, can we create such a container with ViewModel LiveData, store the data and access it from anywhere?例如,我们可以用 ViewModel LiveData 创建这样一个容器,存储数据并从任何地方访问它吗?

Shared ViewModel in Android to communicate with other fragments.在 Android 中共享 ViewModel 以与其他片段进行通信。 You can save your all data in this SharedViewModel and acsess it in all the fragments.您可以将所有数据保存在此 SharedViewModel 中并在所有片段中对其进行访问。

Please follow this link https://www.geeksforgeeks.org/shared-viewmodel-in-android/请点击此链接https://www.geeksforgeeks.org/shared-viewmodel-in-android/

Here they have used two fragment which act as sender and receiver similarly you can create for your multiple fragments在这里他们使用了两个片段作为发送者和接收者,你可以为你的多个片段创建类似的

//Java Implementation of SharedViewModel //SharedViewModel的Java实现

Sharing data between fragments using new architecture component ViewModel 使用新架构组件 ViewModel 在片段之间共享数据

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM