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

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

最好的处理方法是什么?


当前回答

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

如果您更喜欢封装或隐藏大部分低级的打包代码,那么您可以考虑使用我在不久前编写的一些代码来简化对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);

其他回答

从api 29开始,你现在可以在Parcel类中使用readBoolean()。 详见https://developer.android.com/reference/android/os/Parcel#readBoolean()

您还可以使用writeValue方法。在我看来,这是最直接的解决办法。

dst.writeValue( myBool );

然后,你可以很容易地检索它与一个简单的转换为布尔:

boolean myBool = (Boolean) source.readValue( null );

实际上,Android框架会把它作为一个整数来处理:

writeInt( (Boolean) v ? 1 : 0 );

在Kotlin中简短而简单的实现,具有可空支持:

为Parcel添加方法

fun Parcel.writeBoolean(flag: Boolean?) {
    when(flag) {
        true -> writeInt(1)
        false -> writeInt(0)
        else -> writeInt(-1)
    }
}

fun Parcel.readBoolean(): Boolean? {
    return when(readInt()) {
        1 -> true
        0 -> false
        else -> null
    }
}

并使用它:

parcel.writeBoolean(isUserActive)

parcel.readBoolean()        // For true, false, null
parcel.readBoolean()!!      // For only true and false

对于API 29及以上,我们可以使用

writeToParcel:

dest writeBoolean (booleanFlag);

readFromParcel:

booleanFlag = in.readBoolean()

或者我们可以用

writeToParcel:

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

readFromParcel:

布尔标志 = in.readbyte() != 0;

我是这么做的……

writeToParcel:

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

readFromParcel:

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