gpt4 book ai didi

java - 如何在Parcelable类中实现读写

转载 作者:行者123 更新时间:2023-12-01 21:27:14 24 4
gpt4 key购买 nike

可分包

我有这个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();
}
}

我尝试自己填充最后一个构造函数,但我不知道如何读取 boolean 值和自定义类的值,就像我的 Card 类,即 Class对于 mValue mCard

我尝试使用它,但仍然不起作用:mCard = in.readValue(Card.class.getClassLoader);

我应该如何编写这两个方法才能使类实现 Parcelable ,就像它应该的那样?

最佳答案

写卡片

out.writeParcelable(mCard, flags);

读取卡片

mCard = (Card) in.readParcelable(Card.class.getClassLoader());
<小时/>

编写 boolean 值

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

读取 boolean 值

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

(这就是 writeValuereadValueBoolean 类型内部工作的方式)

关于java - 如何在Parcelable类中实现读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37931479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com