如何实现写&阅读Parcelable Class

时间:2016-06-20 20:43:24

标签: java android parcelable

Parcelable

我有Player班级:

public class Player implements Parcelable {
private String mName; // Player's name
private Card mCard; // Player's current card
private boolean mLifeStatus = true; // Player's life status
private boolean mProtected = false; // If the Player's been protected by the guard or not
private int mId; // ID of the Player
private int mCount;

/* 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.writeString(mName);
    out.writeValue(mCard);
    out.writeValue(mLifeStatus);
    out.writeValue(mProtected);
    out.writeInt(mId);
    out.writeInt(mCount);
}

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

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

// example constructor that takes a Parcel and gives you an object populated with it's values
private Player(Parcel in) {
    mName = in.readString();
    mCard = in.readValue();
    mLifeStatus = in.readValue(mLifeStatus);
    mProtected = in.readValue(mProtected);
    mId = in.readInt();
    mCount = in.readInt();
}
}

我试图自己填写最后一个构造函数,但我不知道如何读取布尔值和自定义类的值,就像我的Card类一样,它是mValue的类mCard

我尝试使用此功能,但仍无效:mCard = in.readValue(Card.class.getClassLoader);

我应该如何编写这两个方法,以使类实现Parcelable它应该如何?

3 个答案:

答案 0 :(得分:1)

Parcel可以存储基本类型和Parcelable对象。这意味着存储在Parcel中的任何内容都必须是基本类型或Parceelable对象。

查看Player的成员数据,我看到一堆原始类型和一种更复杂的类型:Card。

要在您的包裹中存储卡,您必须使卡类可以使用。

或者,如果Player类可以访问Card的内部细节,您可以编写代码从Card中提取原始类型并存储它们,然后在读取方面,将原始类型从包中拉出并使用它们建一张卡片。这种技术只有在卡足够简单以至于不用担心违反封装时才有效。

答案 1 :(得分:1)

写卡

out.writeParcelable(mCard, flags);

阅读卡片

mCard = (Card) in.readParcelable(Card.class.getClassLoader());

编写布尔

out.writeInt(mLifeStatus ? 1 : 0);
out.writeInt(mProtected ? 1 : 0);

阅读布尔

mLifeStatus = in.readInt() == 1;
mProtected = in.readInt() == 1;

(这是writeValuereadValue内部Boolean类型工作的方式

答案 2 :(得分:-1)

writeToParcel:

dest.writeByte((byte) (myBoolean ? 1 : 0));  

readFromParcel:

myBoolean = in.readByte() != 0; 

参考:https://stackoverflow.com/a/7089687/4577267