有一个接口DrawingElement
(扩展Parcelable
)有多个实现。另一个类中有一个字段List<DrawingElement> elements
,它实现Parcelable
。因此List应该写入Parcel,但是读取Parcelable ArrayList的方法需要一个具体的类来引用Creator的具体实现,这不起作用:in.createTypedArrayList(DrawingElement.CREATOR)
。
public interface DrawingElement extends Parcelable {
}
public class FirstDrawingElementImpl implements DrawingElement {
@Override
public void writeToParcel(Parcel dest, int flags) {
// done easily.
}
}
public class SecondDrawingElementImpl implements DrawingElement {
@Override
public void writeToParcel(Parcel dest, int flags) {
// done easily.
}
}
public class DrawingElementsContainer implements Parcelable {
private List<DrawingElement> elements;
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO:
}
}
有什么建议吗?
更新
如果我必须使用@pskink建议,我必须做一些奇怪的演绎:
protected Drawing(Parcel in) {
DrawingElement[] parcelables = (DrawingElement[]) in.readParcelableArray(DrawingElement.class.getClassLoader());
elements = new ArrayList<>(Arrays.asList(parcelables));
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelableArray(elements.toArray(new Parcelable[elements.size()]), flags);
}
dest.writeList(elements)
是明显的决定,但我通过传递接口类加载器感到困惑。
答案 0 :(得分:0)
使用以下代码定义您的课程。 parcel.readArrayList
方法用于从包中读取列表,parcel.wrtieList
方法用于将列表写入包。 Refer this answer
public class DrawingElementsContainer implements Parcelable {
private ArrayList<DrawingElement> elements;
public DrawingElementsContainer(Parcel in) {
elements=in.readArrayList(DrawingElement.class.getClassLoader());
}
public ArrayList<DrawingElement> getElements() {
return elements;
}
public void setElements(ArrayList<DrawingElement> elements) {
this.elements = elements;
}
@Override
public int describeContents() {
return 0;
}
public DrawingElementsContainer()
{
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(elements);
}
public static final Parcelable.Creator<DrawingElementsContainer> CREATOR
= new Parcelable.Creator<DrawingElementsContainer>() {
public DrawingElementsContainer createFromParcel(Parcel in) {
return new DrawingElementsContainer(in);
}
public DrawingElementsContainer[] newArray(int size) {
return new DrawingElementsContainer[size];
}
};
}
希望它可以帮到你