您的位置:首页 > 移动开发 > Android开发

Android 通过Intent 传递对象

2011-09-21 14:52 537 查看
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
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    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();
    }
}

Once you have your objects implement
Parcelable
it's just a matter of putting them into yourIntents with

putExtra():

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

Then you can pull them back out with
getParcelableExtra():

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


   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息