Android 中的 Parcelable 和继承 [英] Parcelable and inheritance in Android
本文介绍了Android 中的 Parcelable 和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个 Parcelable 的实现,它为不涉及继承的单个类工作.当涉及到继承时,我在找出实现接口的最佳方法时遇到了问题.假设我得到了这个:
I got an implementation of Parcelable working for a single class that involves no inheritance. I have problems figuring out the best way to implement the interface when it come to inheritance. Let's say I got this :
public abstract class A {
private int a;
protected A(int a) { this.a = a; }
}
public class B extends A {
private int b;
public B(int a, int b) { super(a); this.b = b; }
}
问题是,为 B 实现 Parcelable 接口的推荐方法是什么(在 A 中?在两者中?如何?)
Question is, which is the recommended way to implement the Parcelable interface for B (in A? in both of them? How?)
推荐答案
这是我最好的解决方案,我很高兴听到有人对此有想法.
Here is my best solution, I would be happy to hear from somebody that had a thought about it.
public abstract class A implements Parcelable {
private int a;
protected A(int a) {
this.a = a;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(a);
}
protected A(Parcel in) {
a = in.readInt();
}
}
public class B extends A {
private int b;
public B(int a, int b) {
super(a);
this.b = b;
}
public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
public B createFromParcel(Parcel in) {
return new B(in);
}
public B[] newArray(int size) {
return new B[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(b);
}
private B(Parcel in) {
super(in);
b = in.readInt();
}
}
这篇关于Android 中的 Parcelable 和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文