2019独角兽企业重金招聘Python工程师标准>>>
1 官方例子
public class MyParcelable implements Parcelable {private int mData;public int describeContents() {return 0;}public void writeToParcel(Parcel out, int flags) {out.writeInt(mData);}public static final Parcelable.Creator<MyParcelable> CREATOR= new Parcelable.Creator<MyParcelable>() {public MyParcelable createFromParcel(Parcel in) {return new MyParcelable(in);}public MyParcelable[] newArray(int size) {return new MyParcelable[size];}};private MyParcelable(Parcel in) {mData = in.readInt();}}
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
2 Parcel里面有带classloader的方法可以直接填null,会使用默认的classloader,但是用null会报异常,原因有待查。
3 Parcel的writeValue方法可以写入Object类型的数据。
父类抽象类 子类复写describeContents方法
public XiangleTree createFromParcel(Parcel source) {
int description = source.readInt();
switch (description) {
case CATEGORY:
Category category = new Category();
category.setId(source.readString());
category.setLevel(source.readString());
category.setName(source.readString());
category.setParentId(source.readString());
category.setHasCoupon(source.readString());
return category;
case CIRCLE:
Circle circle = new Circle();
circle.setId(source.readString());
circle.setLevel(source.readString());
circle.setName(source.readString());
circle.setParentId(source.readString());
circle.setHasCoupon(source.readString());
return circle;
default:
return null;
}
}
回答者还笑称Parcelable 接口是个C++的程序员设计的,结果发现JAVA中没有多重继承。
5 Parcelable 的CONTENTS_FILE_DESCRIPTOR变量http://stackoverflow.com/questions/4076946/parcelable-where-when-is-describecontents-used
FileDescriptor
object into Parceable you should/must specify CONTENTS_FILE_DESCRIPTOR as return value of describeContents(), i.e. by "special object" (indescribeContents()
's description) they really mean: FileDescriptor
.
6 Parcelable 的PARCELABLE_WRITE_RETURN_VALUE变量用在writeToParcel (Parcel dest, int flags)方法。flags的值可以是0 or PARCELABLE_WRITE_RETURN_VALUE
.
dest是某个方法的返回值such as "Parcelable someFunction()
", "void someFunction(out Parcelable)
", or "void someFunction(inout Parcelable)
"
7 处理list:writeToParcel方法dest.writeTypedList(xxList) createFromParcel方法:source.readTypedList(xxList,XX.CREATOR),或者参考《树形对象实现parcelable接口》
8 树形对象实现Parcelable 见笔记 《树形对象实现parcelable接口》