Android Parcelable的简单使用

转自https://www.jianshu.com/p/df35baa91541
1.Parcelable的介绍
进行Android开发的时候,无法将对象的引用传给Activities或者Fragments,我们需要将这些对象放到一个Intent或者Bundle里面,然后再传递。简单来说就是将对象转换为可以传输的二进制流(二进制序列)(可存储或可传输的状态)的过程,这样我们就可以通过序列化,转化为可以在网络传输或者保存到本地的流(序列),从而进行传输数据 ,那反序列化就是从二进制流(序列)转化为对象的过程.
Parcelable是Android为我们提供的序列化的接口,使用Parcelable可以在进程间传递一个自定义的较为复杂的对象。比如,将一个对象如GroupInfo,从一个程序传递到launcher中,就需要使用到Parcelable。

2.Parcelable的使用

GroupInfo可以包含GroupName,GroupNumber,IsFastGroup;

要将GroupInfo在进程间传递,要对其实现序列化,在Android中实现Parcelable接口。在Parcelable接口中,我们需要的主要方法有writeToParcel,describeContents,Parcelable.Creator<?>。完成序列化,即将对象转换为二进制流的是writeToParcel。完成反序列化,即将二进制流转换为对象的是Parcelable.Creator<?>。
下面来看这么一段代码,GroupInfo类实现了Parcelable接口

public class GroupInfo implements Parcelable{
   int mIsFastGroup = 0;
   String mGroupName;
   String mGroupNumber;
   public GroupInfo(String name, String num, int fastGroup){
     mGroupName = name;
     mGroupNumber = num;
     mIsFastGroup  = fastGroup;
   }
   public GroupInfo(Parcel parcel){
     mGroupName = parcel.readString();
     mGroupNumber = parcel.readString();
     mIsFastGroup  = parcel.readInt();
   }
   //返回内容描述信息,一般返回0;
   @Override
   public int describeContents(){
        return 0;
   }
   //序列化
    @Override
    public int writeToParcel(Parcel arg0, int arg1){
       arg0.writeString(mGroupName );
       arg0.writeString(mGroupNumber );
        arg0.writeInt(mIsFastGroup  );
    }
    //反序列化
    public static final Creator<GroupInfo> CREATOR = new Creator<GroupInfo>(){
    //创建指定长度的原始对象数组
     @Override
     public GroupInfo[] newArray(int size){
        return new GroupInfo[size];
     }
     //从序列化对象中,获取原始的对象
     @Override
     public GroupInfo createFromParcel(Parcel  parcel){
        GroupInfo group = new GroupInfo(parcel);
        return group;
     }
   }
    

} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值