android之Parceable

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

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

那现在我们来看下Parcelable接口实现要点:

1.    describeContents方法,只要返回0即可:

public int describeContents() {
        return 0;
    }

2.writeToParcel方法,该方法是将类中定义的数据写入外面提供的Parcel中,就是将数据保存在Parcel中,Parcel提供了很多的读写方法,

如要写入的数据是String,就用(Parcel)dest.writeString,要写入int就用writeInt,等等:

 public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(operatorAlphaLong);
        dest.writeString(operatorAlphaShort);
        dest.writeString(operatorNumeric);
        dest.writeSerializable(state);
    }

3.Creator方法,该方法要实现两个接口:createFromParcel和newArray。

createFromParcel(Parcel in)就是从外部Parcel读取数据,来实例化本类,与上面writeToParcel方法中的写入相对应来读取数据

newArray(int size)就是创建一个size大小的本类数组

    public static final Creator<NetworkInfo> CREATOR =
        new Creator<NetworkInfo>() {
            public NetworkInfo createFromParcel(Parcel in) {
                NetworkInfo netInfo = new NetworkInfo(
                        in.readString(), /*operatorAlphaLong*/
                        in.readString(), /*operatorAlphaShort*/
                        in.readString(), /*operatorNumeric*/
                        (State) in.readSerializable()); /*state*/

//这里要注意顺序与写入的一致

//**************************************************

这里我们常常还有这样的写法:

        public Rect createFromParcel(Parcel in) {

  //这里的Rect就是实现Parcelable接口的这个类
        Rect r = new Rect();
        r.left = in.readInt();
        r.top = in.readInt();
        r.right = in.readInt();
        r.bottom = in.readInt();
        return r;
        }

//**************************************************

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值