实现Parcelable接口
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();}}實現 Parcelable 的兩個方法,同時還要實現靜態變量CREATOR。 其他入門例子:
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類型的數據。
4 describeContents方法的用處 http://stackoverflow.com/questions/4778834/purpose-of-describecontents-of-parcelable-interface 主要就是用來區分子類的父類抽象類 子類復寫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; } }http://stackoverflow.com/questions/4076946/parcelable-where-when-is-describecontents-used
回答者還笑稱Parcelable 接口是個C++的程序員設計的,結果發現JAVA中沒有多重繼承。
5 Parcelable 的CONTENTS_FILE_DESCRIPTOR變量http://stackoverflow.com/questions/4076946/parcelable-where-when-is-describecontents-used
If you need to put 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接口》
轉載于:https://my.oschina.net/dingbuoyi/blog/61903
總結
以上是生活随笔為你收集整理的实现Parcelable接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到怀孕生小孩是怎么回事
- 下一篇: apue源码编译