Intent传递简单对象与集合

来源:互联网 发布:今日头条济南数据分析 编辑:程序博客网 时间:2024/06/05 13:23

们在Intent传递传递对象,可以有三种方式,实现Serializable接口、实现Parcelable接口,使用json格式序列化与反序列化。

  在此我们使用第二方式,现实Parcelable接口,实现Parcelable需要以下操作。

   1.writeToParcel 方法:该方法将类的数据写入外部提供的Parcel中。

   2.describeContents 方法:返回内容描述信息的资源ID。

   3.静态的Parcelable.Creator接口,本接口有以下方法两方法: 

                         3.1 createFormParcel(Parcel in):实现从parcle实例中创建出类的实例的功能。

                         3.2 newArray(int size): 创建一个类型为T,长度为size的数组。

 www.wwkxii.com

例子1:User 对象创建

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class User implements Parcelable{  
  2.   
  3.     private Integer userId;  
  4.     private String  userName;  
  5.     @Override  
  6.     public int describeContents() {  
  7.         return 0;  
  8.     }  
  9.       
  10.     /**  
  11.      * 注意:序列化与反序列化顺序必须要一样  
  12.      * @param parcel  
  13.      */  
  14.     public User(Parcel source){  
  15.         this.userId =source.readInt();  
  16.         this.userName = source.readString();  
  17.     }  
  18.       
  19.       
  20.       
  21.     public User(Integer userId, String userName) {  
  22.         super();  
  23.         this.userId = userId;  
  24.         this.userName = userName;  
  25.     }  
  26.   
  27.     /**  
  28.      * 序列化  
  29.      */  
0 0
原创粉丝点击