如何使用Parcelable传递可空的对象列表

问题描述 投票:1回答:2

我想传递一个自定义对象,该对象具有其他自定义对象的可空列表。如何绕过这个。我正在使用Kotlin

当列表为空时,writeTypedList和createTypedArrayList不起作用

android kotlin parcelable
2个回答
1
投票

非常简单,只需要在列表不为空时才需要读取列表。

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);
}

0
投票

如何发送自定义对象列表,而自定义对象又由自定义对象组成?

您需要为您创建的链接中的每个自定义对象实现Parcelable interface

dest.writeTypedList(customList) // in write to parcel 

this.customList = in.createTypedArrayList(CustomObject.CREATOR) // in the constructor which receives (Parcel in) as parameter

请记住,不要错过在链接中实现parcelable接口的任何对象。

© www.soinside.com 2019 - 2024. All rights reserved.