Android源码学习系列--Parcelable

本文详细介绍了如何实现Android应用中的Parcelable接口,包括描述内容、写入Parcel和创建Parcelable对象的方法,以及Parcelable.Creator接口的使用。通过示例代码,深入理解Parcelable在Android开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现了该接口的类可以被写入保存在Parcel中。如果实现该接口需要有一个实现了ParcelCreator接口的静态字段CREATOR

一个典型的实现如下:

public class MyParcelable implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } }

/** * Flag for use with writeToParcel(Parcel, int): the object being written is a return value, that is the result of a function such as "Parcelable someFunction()", "void *someFunction(out Parcelable)", or "void someFunction(inout Parcelable)". */ public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001; /** * 方法describeContents()使用的掩码。在分组时,每位都被认为是有潜在特殊含义的 */ public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001; /** *对象在Parcelable中特定的编码形式 */ public int describeContents(); /** * 将对象拼合进Parcel中 */ public void writeToParcel(Parcel dest, int flags); /** * 上面提到的CREATOR字段必须实现的接口 */ public interface Creator<T> { /** *创建一个Parcelable对象,并将之前Parcelable.writeToParcel()写入到Parcel中的对象实例化并返回 */ public T createFromParcel(Parcel source); /** * 创建一个Parcelable对象数组 */ public T[] newArray(int size); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值