android ia 教程,Android Parcelable - Write and read ArrayList< IA > when IA is a interface

问题

I have a interface IA and class B and C that implement them.

Both B and C implement Parcelable as well.

Then I have the tricky part:

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.

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

I've tried to write (ArrayList) 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.

Any ideas?

@SuppressWarnings("unchecked")

public D (Parcel in) {

list = new ArrayList();

(...)

list = (ArrayList) 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);

}

回答1:

@SuppressWarnings("unchecked")

public D (Parcel in) {

list = new ArrayList();

(...)

//ERROR -> list = (ArrayList) 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);

}

回答2:

I recommend you to install "Android Parcelable code generator" plugin. After this you can generate writeToParcel function, constructor which reads from parcel and creator class only whith clicking Alt+Insert buttons.

来源:https://stackoverflow.com/questions/15543924/android-parcelable-write-and-read-arraylist-ia-when-ia-is-a-interface

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值