本文介绍了Android Parcelable - 写入和读取 ArrayList<IA>当 IA 是一个接口时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口 IA 和实现它们的 BC 类.B 和 C 都实现了 Parcelable.

I have a interface IA and class B and C that implement them.Both B and C implement Parcelable as well.

然后是棘手的部分:

D 类有一个 ArrayList.我也需要在 arraylist 中插入 B 类和 C 类.它们共享相同的结构,但 IS-A" 关系不适用.

Class D has a ArrayList< IA >. I need this too insert both classes B and C in the arraylist. They share the same structure but the "IS-A" relation don't apply.

我需要将 D 作为包裹从一个活动传递到另一个活动.

I need to pass D from one activity to another as a Parcel.

我尝试在.readSerializable 中编写(ArrayList),但我得到了一个IOException.我知道如果 IA 不是接口,问题就很简单,但我似乎无法找到一个简单的解决方案.

I've tried to write (ArrayList<IA>) in.readSerializable but I got a IOException. I know that if IA was not a interface the problem was easy, but I can't seem to find an easy solution for this.

有什么想法吗?

@SuppressWarnings("unchecked")
public D (Parcel in) {
    list = new ArrayList<IA>();
    (...)    
    list = (ArrayList<IA>) in.readSerializable 
    }

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
    public D createFromParcel(Parcel in) {
        return new D(in);
    }

    public D[] newArray(int size) {
        return new D[size];
    }
};

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    (...)
    dest.writeList(list);
}

推荐答案

    @SuppressWarnings("unchecked")
public D (Parcel in) {
    list = new ArrayList<IA>();
    (...)    
    //ERROR -> list = (ArrayList<IA>) in.readSerializable 
    list = in.readArrayList(IA.class.getClassLoader());
}

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
    public D createFromParcel(Parcel in) {
        return new D(in);
    }

    public D[] newArray(int size) {
        return new D[size];
    }
};

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    (...)
    dest.writeList(list);
}

这篇关于Android Parcelable - 写入和读取 ArrayList<IA>当 IA 是一个接口时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 03:31