如何使用 Parcelable 传递可为空的对象列表
How do you pass a nullable list of objects with Parcelable
我想传递一个自定义对象,该对象具有其他自定义对象的可为空列表。我该如何解决这个问题。我正在使用 Kotlin
当列表为空时,writeTypedList 和 createTypedArrayList 不起作用
How to send a list of custom objects which in turn consists of custom objects ?
您需要为您创建的 link 中的 每个 自定义对象实施 Parcelable interface
。
dest.writeTypedList(customList) // in write to parcel
和
this.customList = in.createTypedArrayList(CustomObject.CREATOR) // in the constructor which receives (Parcel in) as parameter
请记住不要遗漏任何对象在link.
中实现parcelable接口
很简单,你只需要读取不为空的列表即可。
dest.writeByte(list == null ? (byte)0 : (byte)1)
if(list != null) {
dest.writeInt(list.size());
dest.writeTypedList(list);
}
然后
boolean hasList = in.readByte() > 0;
if(hasList) {
int size = in.readInt();
List<MyObj> list = new ArrayList<>(size);
in.readTypedList(list, MyObj.CREATOR);
}
我想传递一个自定义对象,该对象具有其他自定义对象的可为空列表。我该如何解决这个问题。我正在使用 Kotlin
当列表为空时,writeTypedList 和 createTypedArrayList 不起作用
How to send a list of custom objects which in turn consists of custom objects ?
您需要为您创建的 link 中的 每个 自定义对象实施 Parcelable interface
。
dest.writeTypedList(customList) // in write to parcel
和
this.customList = in.createTypedArrayList(CustomObject.CREATOR) // in the constructor which receives (Parcel in) as parameter
请记住不要遗漏任何对象在link.
中实现parcelable接口很简单,你只需要读取不为空的列表即可。
dest.writeByte(list == null ? (byte)0 : (byte)1)
if(list != null) {
dest.writeInt(list.size());
dest.writeTypedList(list);
}
然后
boolean hasList = in.readByte() > 0;
if(hasList) {
int size = in.readInt();
List<MyObj> list = new ArrayList<>(size);
in.readTypedList(list, MyObj.CREATOR);
}