如何使用 Intent 将对象从一个 Android Activity 发送到另一个? [英] How to send an object from one Android Activity to another using Intents?

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

问题描述

如何从一个 Activity 到另一个使用 类的 putExtra() 方法意图?

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

推荐答案

如果你只是传递对象,那么 Parcelable 就是为此而设计的.与使用 Java 的本机序列化相比,它需要更多的努力来使用,但速度更快(我的意思是,WAY 更快).

If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).

从文档中,如何实现的一个简单示例是:

From the docs, a simple example for how to implement is:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

请注意,如果您有多个字段要从给定的 Parcel 中检索,您必须按照放入它们的相同顺序(即采用 FIFO 方法)执行此操作.

Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).

一旦您的对象实现了 Parcelable,只需将它们放入您的 Intents 带有 putExtra():

Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

然后你可以用 getParcelableExtra():

Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

如果您的对象类实现了 Parcelable 和 Serializable,那么请确保您强制转换为以下之一:

If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:

i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);

这篇关于如何使用 Intent 将对象从一个 Android Activity 发送到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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