Android:如何传递 ArrayList<object>从一项活动到另一项活动 [英] Android: how to pass ArrayList&lt;object&gt; from an activity to another

查看:18
本文介绍了Android:如何传递 ArrayList<object>从一项活动到另一项活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

arraylist 中的对象是在外部库中定义的.该对象包含一些 int 值和一个 float[].

The object in the arraylist is defined in an external library. The object contains some int values and also a float[].

如何将所有 ArrayList 从一个活动传递到另一个活动?谢谢!

How can I pass all the ArrayList from an activity to another? Thanks!

顺便说一下,我没有对象类的控制权.

By the way, I do not have the control of the object class.

推荐答案

这取决于数组列表中的对象类型.如果您可以控制它并且可以让它实现 Parcelable,那么您可以使用 Intent.putParcelableArrayListExtra.

It depends on the type of object that's in the array list. If you have control over it and can have it implement Parcelable, then you can use Intent.putParcelableArrayListExtra.

另一种方法是扩展应用程序并将您的 ArrayList 存储在那里.然后它不需要在 Intent 中传递,应用程序中的所有活动都可以通过调用 getApplication() 来访问它.Application 对象将在应用程序的整个生命周期内持续存在,其中存储的任何数据也将如此.

Another approach is to extend Application and store your ArrayList there. It then doesn't need to be passed in the Intent, and all activities in the application can access it by calling getApplication(). The Application object will persist for the life of the application, as will any data stored in it.

为此使用 Application 对象:

To use an Application object for this:

  1. 编写一个扩展 android.app.Application 的类(我们称之为 MyApplication).声明一个字段(我们称之为 array)来保存你的数组列表.
  2. 在清单的 标记中指定名称 MyApplication.系统会在为您的应用创建进程时创建 MyApplication 的实例.
  3. 任何希望访问该字段的活动都可以使用 ((MyApplication) getApplication()).array.您在第一个活动中初始化它并在第二个活动中检索它.
  1. Write a class (let's call it MyApplication) that extends android.app.Application. Declare a field (let's call it array) to hold your array list.
  2. Specify the name MyApplication in the manifest's <application> tag. An instance of MyApplication will be created by the system when it creates the process for your app.
  3. Any activity that wishes to access the field can use ((MyApplication) getApplication()).array. You initialize it in the first activity and retrieve it in the second.

另一种完全不同的方法是在某个类中声明一个静态单例.文档实际上建议将其子类化为更模块化的应用程序.这有点像黑客,因为它基本上是在声明一个全局变量.但我想这只不过是将随机数据放入 Application 对象中.

Another completely different approach is to declare a static singleton in some class. The docs actually recommend this over subclassing Application as being more modular. It's kind of a hack because it's basically declaring a global variable. But I suppose it's no more of a hack than putting random data in an Application object.

这篇关于Android:如何传递 ArrayList<object>从一项活动到另一项活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆