简体   繁体   English

如何在 Android 中的多个活动和片段中保留对象?

[英]How to keep objects throughout multiple activities and fragments in Android?

I created a class "Car" and I have a list of instantiated Cars created in my MainActivity.我创建了一个“汽车”类,并且在我的 MainActivity 中创建了一个实例化的汽车列表。 I have a master/detail flow with an ItemListActivity as well, which should be able to receive a specific car from MainActivity.我也有一个带有 ItemListActivity 的主/细节流,它应该能够从 MainActivity 接收特定的汽车。

This master/detail flow works as a Settings Menu, where there are multiple fragments acting as different types of settings (Build, engine, etc.)这个主/细节流作为一个设置菜单,其中有多个片段作为不同类型的设置(构建、引擎等) 在此处输入图片说明

The master/detail flow needs to then get all the changes made to the edit text, and update the fields of the Car that it received, and than send it back to MainActivity.然后,主/细节流需要获取对编辑文本所做的所有更改,并更新它收到的 Car 的字段,然后将其发送回MainActivity。

I'm not sure if this is 1) possible or 2) the best way to approach this problem.我不确定这是否是 1) 可能或 2) 解决此问题的最佳方法。 Should I be keeping the list of objects in MainActivity?我应该在 MainActivity 中保留对象列表吗? Is there a better way to keep an object that will be used globally?有没有更好的方法来保留将在全球范围内使用的对象?

I would recommend having a ViewModel in your activity and get the ViewModel instance from your fragments as follows.我建议在您的活动中使用ViewModel并从您的片段中获取ViewModel实例,如下所示。

carViewModel = ViewModelProviders.of(getActivity()).get(CarViewModel.class);

The CarViewModel might have the necessary elements to build a car and from each fragments, you can just update that ViewModel that resides in your activity. CarViewModel可能具有构建汽车的必要元素,并且您可以根据每个片段更新位于您的 Activity 中的ViewModel

The CarViewModel might have a function call buildCar that you can trigger when you are done building your car from different fragments. CarViewModel可能有一个函数调用buildCar ,当您完成从不同片段构建汽车时可以触发它。 The ViewModel will be bound to the lifecycle of the activity and hence if you close the activity, the information will be lost. ViewModel将绑定到活动的生命周期,因此如果您关闭活动,信息将丢失。

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

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