如何在Parcelable中实现读写Class

How to implement the write & read in Parcelable Class

可包裹

我有这个 Player Class:

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();
}
}

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

的 Class

我尝试使用这个但还是不行:mCard = in.readValue(Card.class.getClassLoader);

我应该如何编写这两个方法才能使 Class 实现 Parcelable 它应有的样子?

writeToParcel:

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

读取包裹:

myBoolean = in.readByte() != 0; 

参考:

Parcel 可以存储原始类型和Parcelable 对象。这意味着存储在 Parcel 中的任何东西都必须是原始类型或 Parceelable 对象。

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

要将卡存储在包裹中,您必须使卡 class 可包裹。

或者,如果玩家 class 可以访问 Card 的内部细节,您可以编写代码将原始类型从 Card 中提取出来并存储它们,然后在读取端,将原始类型从 Card 中提取出来包裹并使用它们来构建卡片。此技术仅在 Card 足够简单以至于您不必担心违反封装时才有效。

写卡片

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 类型工作的方式)