android Parcelable中boolean与枚举的写法

来源:互联网 发布:联通云计算公司 编辑:程序博客网 时间:2024/05/21 13:56

Android 中经常用到自定义类实现Serializable与Parcelable接口,通过Intent在各个组件之间传递数据。而Parcelable接口要优于Serializable接口,但也相对难写。

一、boolean的写法

Parcel只有一个writeBooleanArray方法是用来写boolean数组的,而boolean我们可以这样写

  parcel.writeByte((byte) (done==true?1:0));

读取的时候,

  done = parcel.readByte()!=0;

当然,我们也可以写int类型,读取时进行相应判断就好。

二、枚举类型的写法

直接上代码:

public enum PostEnum implements Parcelable {    PostPre,PostIng,PostError,PostSuccess;    @Override    public int describeContents() {        // TODO Auto-generated method stub        return 0;    }    @Override    public void writeToParcel(Parcel dest, int flags) {        dest.writeInt(ordinal());    }    public static final Creator<PostEnum> CREATOR = new Creator<PostEnum>() {        @Override        public PostEnum createFromParcel(Parcel in) {            return  PostEnum.values()[in.readInt()];        }        @Override        public PostEnum[] newArray(int size) {            return new PostEnum[size];        }    };}

在实体类中写入与读取时

//写入,writeToParcel方法中dest.writeParcelable(postEnum, flags);//读取,构造方法中postEnum = in.readParcelable(PostEnum.class.getClassLoader());
原创粉丝点击