Parcel和Parcelable

参考: http://blog.csdn.net/dairyman000/article/details/7247619

arcel 在英文中有两个意思,其一是名词,为包裹,小包的意思; 其二为动词,意为打包,扎包。邮寄快递中的包裹也用的是这个词。Android采用这个词来表示封装消息数据。这个是通过IBinder通信的消息的载 体。需要明确的是Parcel用来存放数据的是内存(RAM),而不是永久性介质(Nand等)。

Parcelable,定义了将数据写入Parcel,和从Parcel中读出的接口。一个实体(用类来表示),如果需要封装到消息中去,就必须实现这一接口,实现了这一接口,该实体就成为“可打包的”了。

接口的定义如下:

复制代码
public interface Parcelable {
    //内容描述接口,基本不用管
    public int describeContents();
    //写入接口函数,打包
    public void writeToParcel(Parcel dest, int flags);
     //读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入。
    //为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例。
    public interface Creator<T> {
           public T createFromParcel(Parcel source);
           public T[] newArray(int size);
    }
}
复制代码

下面定义了一个简单类People, 他需要把自身的数据,打入包中。 同时在消息的接收方需要通过People实现的Parcelable接口,将People重新构造出来。

复制代码
People.java
public class People implements Parcelable {
    private String name = null;
    private int age = 0;
    private int sex = 0;// 0代表男、1代表女

    public People() {
        super();
    }

    public People(String name, int age, int sex) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeInt(sex);
    }

    public static final Parcelable.Creator<People> CREATOR = new Creator<People>() {

        @Override
        public People[] newArray(int size) {
            return new People[size];
        }

        @Override
        public People createFromParcel(Parcel source) {
            return new People(source.readString(), source.readInt(),
                    source.readInt());
        }
    };
}
复制代码

传递People

复制代码
//发送 MainActivity.java
People people = new People();
people.setName("张三");
people.setSex(Integer.parseInt(0));
people.setAge(Integer.parseInt(25));
Intent intent = new Intent(MainActivity.this, ShowActivity.class);
Bundle b = new Bundle();
b.putParcelable("people", people);
intent.putExtras(b);
MainActivity.this.startActivity(intent);

//接受 ShowActivity.java
if(getIntent().getExtras().containsKey("people")){
  People people = getIntent().getExtras().getParcelable("people");
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值