반응형
Android의 Parcelable 및 상속
상속이없는 단일 클래스에 대해 작동하는 Parcelable 구현이 있습니다. 상속과 관련하여 인터페이스를 구현하는 가장 좋은 방법을 찾는 데 문제가 있습니다. 내가 이것을 얻었다 고하자 :
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에서? 둘 다에서? 어떻게?).
여기에 내 최선의 해결책이 있습니다. 그것에 대해 생각한 누군가의 의견을 듣게되어 기쁩니다.
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();
}
}
이것은 내 변형입니다. 가상 읽기 및 쓰기 방법 간의 대칭을 매우 명확하게 보여주기 때문에 좋은 것 같습니다.
참고 : Google은 Parcelable 인터페이스를 디자인하는 데 정말 열악한 작업을 수행했다고 생각합니다.
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);
}
public void readFromParcel(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) {
B b = new B();
b(in);
return b;
}
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);
}
public void readFromParcel(Parcel in) {
super(in);
b = in.readInt();
}
}
다음은 클래스 B가 int 이외의 다른 유형을 가진 둘 이상의 객체를 가질 가능성이 있기 때문에 실제 설정에서 클래스 A에 대한 구현입니다.
It uses reflection to get the types. Then uses a sorting function to sort the fields so that reading and writing happen in the same order.
https://github.com/awadalaa/Android-Global-Parcelable
참고URL : https://stackoverflow.com/questions/4049627/parcelable-and-inheritance-in-android
반응형
'Development Tip' 카테고리의 다른 글
document.cookie에 사이트의 모든 쿠키가 표시되지 않는 이유는 무엇입니까? (0) | 2020.12.01 |
---|---|
__setstate__ 및 __getstate__ 사용의 간단한 예 (0) | 2020.12.01 |
목록 이해력을 사용하여 튜플 작성 (0) | 2020.12.01 |
Kubernetes (kubectl)에 사용자를 추가하는 방법은 무엇입니까? (0) | 2020.12.01 |
pycharm에서 Conda 환경 사용 (0) | 2020.12.01 |