Parcelable

来源:互联网 发布:行知外国语校长朱萍 编辑:程序博客网 时间:2024/05/16 13:42

     android整个上层java开发框架可以分为四个方面:界面(activity和appwidget)、消息(Intent和Message)、服务(Service)和数据(Sqllite、Content Provider)。

开发要点摘记:

    1、新的序列化方式:

     android提供了一种新的类型:Parcel。本类被用作封装数据的容器,封装后的数据可以通过Intent或IPC传递。

     除了基本类型以外,只有实现了Parcelable接口的类才能被放入Parcel中。

Parcelable实现要点:需要实现三个东西

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

writeToParcel (Parcel dest, int flags) 具体参数含义见javadoc

2)describeContents方法。没搞懂有什么用,反正直接返回0也可以

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

createFromParcel(Parcel in) 实现从in中创建出类的实例的功能

newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话(return new T[size])即可。估计本方法是供外部类反序列化本类数组使用。

示例:

    需求:我们经常需要在多个部件(activity或service)之间通过Intent传递一些数据,简单类型(如数字、字符串)的可以直接放入Intent。复杂类型(例如,J2ee中的Bean)的必须实现Parcelable接口。示例如下:

class SampleBean implements Parcelable

{

    private Bundle mBundle=new Bundle(); 
    public String getArriveTime() 
    {        
        return mBundle.getString("arriveTime"); 
    }

    public String getOlTime() 
    { 
        return mBundle.getString("olTime"); 
    }

    public void setArriveTime(String arriveTime) 
    { 
        this.mBundle.putString("arriveTime", arriveTime); 
    }

    public void setOlTime(String olTime) 
    { 
        this.mBundle.putString("olTime", olTime); 
    }

public int describeContents() 
    { 
        // TODO Auto-generated method stub 
        return 0; 
    }

public void writeToParcel(Parcel out, int arg1) 
    { 
        // TODO Auto-generated method stub 
        out.writeBundle(this.mBundle); 
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 
        public TrainInfo createFromParcel(Parcel in) 
        { 
            SampleBean ti=new SampleBean(); 
            ti.mBundle=in.readBundle(); 
            return ti; 
        }

        public SampleBean[] newArray(int size) 
        { 
            return new SampleBean[size]; 
        } 
    };

}

这里采用Bundle是因为在Parcel中并没有key的概念存在,而Bundle相当于Map。

原创粉丝点击