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

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

最好的处理方法是什么?


当前回答

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

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

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

其他回答

您可以使用屏蔽和移位将布尔值打包到一个字节中。这是最有效的方法,也可能是他们希望你做的。

这个问题已经被其他人完美地回答了,如果你想自己做的话。

如果您更喜欢封装或隐藏大部分低级的打包代码,那么您可以考虑使用我在不久前编写的一些代码来简化对parcelables的处理。

给包裹写信很简单:

parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);

例如,其中color是enum, isDriving是boolean。

从包裹中阅读也不难:

color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
isDriving = (Boolean)unparcelValue();

看看我添加到项目中的“parceldroideexample”。

最后,它还使CREATOR初始化项保持简短:

public static final Parcelable.Creator<Car> CREATOR =
    Parceldroid.getCreatorForClass(Car.class);

我是这么做的……

writeToParcel:

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

readFromParcel:

myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0
out.writeInt(mBool ? 1 : 0); //Write
this.mBool =in.readInt()==1; //Read

你这样声明

 private boolean isSelectionRight;

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

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