更新时间:2023-11-18 08:57:58
您需要使用 Parcel.writeTypedArray()
方法写入阵列,并与读回 Parcel.createTypedArray()
的方法,像这样:
You need to write the array using the Parcel.writeTypedArray()
method and read it back with the Parcel.createTypedArray()
method, like so:
MyClass[] mObjList;
public void writeToParcel(Parcel out) {
out.writeTypedArray(mObjList, 0);
}
private void readFromParcel(Parcel in) {
mObjList = in.createTypedArray(MyClass.CREATOR);
}
为什么你不应该使用 readParcelableArray()
/ writeParcelableArray()
方法的原因是, readParcelableArray()
真正创建一个 Parcelable []
结果。这意味着你可以不投的方法的结果为 MyClass的[]
。相反,你必须创建相同的长度作为结果的 MyClass的
数组和复制的每个元素从结果数组的 MyClass的
阵列。
The reason why you shouldn't use the readParcelableArray()
/writeParcelableArray()
methods is that readParcelableArray()
really creates a Parcelable[]
as a result. This means you cannot cast the result of the method to MyClass[]
. Instead you have to create a MyClass
array of the same length as the result and copy every element from the result array to the MyClass
array.
Parcelable[] parcelableArray =
parcel.readParcelableArray(MyClass.class.getClassLoader());
MyClass[] resultArray = null;
if (parcelableArray != null) {
resultArray = Arrays.copyOf(parcelableArray, parcelableArray.length, MyClass[].class);
}