如何在 Android 上将对象从一个活动传递到另一个活动? [英] How do I pass an object from one activity to another on Android?

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

问题描述

我需要能够在我的应用程序中的多个活动中使用一个对象,并且它必须是相同对象.做这个的最好方式是什么?

I need to be able to use one object in multiple activities within my app, and it needs to be the same object. What is the best way to do this?

我曾尝试将对象设为公共静态",以便其他活动可以访问它,但出于某种原因,这并没有削减它.还有其他方法吗?

I have tried making the object "public static" so it can be accessed by other activities, but for some reason this just isn't cutting it. Is there another way of doing this?

推荐答案

当你创建一个 Intent 对象时,你可以利用以下两种方法用于在两个活动之间传递对象.

When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.

放置包裹

putSerializable

您可以让您的类实现 Parcelable可序列化.然后您可以在活动中传递您的自定义类.我发现这非常有用.

You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.

这是我正在使用的一小段代码

Here is a small snippet of code I am using

CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);

并且在新启动的活动代码中将是这样的...

And in newly started activity code will be something like this...

Bundle b = this.getIntent().getExtras();
if (b != null)
    mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);

这篇关于如何在 Android 上将对象从一个活动传递到另一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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