我试图使一个数组列表Parcelable,以便传递给一个活动的自定义对象列表。我开始写一个myObjectList类,它扩展了ArrayList<myObject>并实现了Parcelable。

MyObject的一些属性是布尔型的,但是Parcel没有任何读写布尔型的方法。

最好的处理方法是什么?


当前回答

out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read

其他回答

out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read

我是这么做的……

writeToParcel:

dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1

readFromParcel:

myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0

在Android (AOSP)源码中有很多这样的例子。例如,PackageInfo类有一个布尔成员requiredForAllUsers,它被序列化如下:

public void writeToParcel(Parcel dest, int parcelableFlags) {
    ...
    dest.writeInt(requiredForAllUsers ? 1 : 0);
    ...
}

private PackageInfo(Parcel source) {
    ...
    requiredForAllUsers = source.readInt() != 0;
    ...
}

你这样声明

 private boolean isSelectionRight;

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

布尔类型需要转换为Parcel支持的东西,所以我们可以将它转换为int。

我通常把它们放在一个数组中,调用writeBooleanArray和readBooleanArray

如果你需要打包一个布尔值,你可以这样做:

parcel.writeBooleanArray(new boolean[] {myBool});