想要在两个activity之间传递对象,那么这个对象必须序列化,android中序列化一个对象有两种方式,一种是实现Serializable接口,这个非常简单,只需要声明一下就可以了,不痛不痒。但是android中还有一种特有的序列化方法,那就是实现Parcelable接口,使用这种方式来序列化的效率要高于实现Serializable接口。不过Serializable接口实在是太方便了,因此在某些情况下实现这个接口还是非常不错的选择。
使用Parcelable步骤:
1.实现Parcelable接口
2.实现接口中的两个方法

public int describeContents();
public void writeToParcel(Parcel dest, int flags);

第一个方法是内容接口描述,默认返回0就可以了
第二个方法是将我们的对象序列化一个Parcel对象,也就是将我们的对象存入Parcel中
3.实例化静态内部对象CREATOR实现接口Parcelable.Creator,实例化CREATOR时要实现其中的两个方法,其中createFromParcel的功能就是从Parcel中读取我们的对象。

也就是说我们先利用writeToParcel方法写入对象,再利用createFromParcel方法读取对象,因此这两个方法中的读写顺序必须一致,否则会出现数据紊乱,一会我会举例子。
看一个代码示例:

public class Person implements Parcelable{private String username;private String nickname;private int age;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(String username, String nickname, int age) {super();this.username = username;this.nickname = nickname;this.age = age;}public Person() {super();}/*** 这里的读的顺序必须与writeToParcel(Parcel dest, int flags)方法中* 写的顺序一致,否则数据会有差错,比如你的读取顺序如果是:* nickname = source.readString();* username=source.readString();* age = source.readInt();* 即调换了username和nickname的读取顺序,那么你会发现你拿到的username是nickname的数据,* 而你拿到的nickname是username的数据* @param source*/public Person(Parcel source) {username = source.readString();nickname=source.readString();age = source.readInt();}/*** 这里默认返回0即可*/@Overridepublic int describeContents() {return 0;}/*** 把值写入Parcel中*/@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeString(username);dest.writeString(nickname);dest.writeInt(age);}public static final Creator<Person> CREATOR = new Creator<Person>() {/*** 供外部类反序列化本类数组使用*/@Overridepublic Person[] newArray(int size) {return new Person[size];}/*** 从Parcel中读取数据*/@Overridepublic Person createFromParcel(Parcel source) {return new Person(source);}};
}

本工程源码http://pan.baidu.com/s/1hqzY3go

最后贴上Parcelable源码,Google已经给了一个示例了:

/** Copyright (C) 2006 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.os;/*** Interface for classes whose instances can be written to* and restored from a {@link Parcel}.  Classes implementing the Parcelable* interface must also have a static field called <code>CREATOR</code>, which* is an object implementing the {@link Parcelable.Creator Parcelable.Creator}* interface.* * <p>A typical implementation of Parcelable is:</p>* * <pre>* 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&lt;MyParcelable&gt; CREATOR*             = new Parcelable.Creator&lt;MyParcelable&gt;() {*         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();*     }* }</pre>*/
public interface Parcelable {/*** Flag for use with {@link #writeToParcel}: the object being written* is a return value, that is the result of a function such as* "<code>Parcelable someFunction()</code>",* "<code>void someFunction(out Parcelable)</code>", or* "<code>void someFunction(inout Parcelable)</code>".  Some implementations* may want to release resources at this point.*/public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;/*** Bit masks for use with {@link #describeContents}: each bit represents a* kind of object considered to have potential special significance when* marshalled.*/public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;/*** Describe the kinds of special objects contained in this Parcelable's* marshalled representation.*  * @return a bitmask indicating the set of special object types marshalled* by the Parcelable.*/public int describeContents();/*** Flatten this object in to a Parcel.* * @param dest The Parcel in which the object should be written.* @param flags Additional flags about how the object should be written.* May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.*/public void writeToParcel(Parcel dest, int flags);/*** Interface that must be implemented and provided as a public CREATOR* field that generates instances of your Parcelable class from a Parcel.*/public interface Creator<T> {/*** Create a new instance of the Parcelable class, instantiating it* from the given Parcel whose data had previously been written by* {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.* * @param source The Parcel to read the object's data from.* @return Returns a new instance of the Parcelable class.*/public T createFromParcel(Parcel source);/*** Create a new array of the Parcelable class.* * @param size Size of the array.* @return Returns an array of the Parcelable class, with every entry* initialized to null.*/public T[] newArray(int size);}/*** Specialization of {@link Creator} that allows you to receive the* ClassLoader the object is being created in.*/public interface ClassLoaderCreator<T> extends Creator<T> {/*** Create a new instance of the Parcelable class, instantiating it* from the given Parcel whose data had previously been written by* {@link Parcelable#writeToParcel Parcelable.writeToParcel()} and* using the given ClassLoader.** @param source The Parcel to read the object's data from.* @param loader The ClassLoader that this object is being created in.* @return Returns a new instance of the Parcelable class.*/public T createFromParcel(Parcel source, ClassLoader loader);}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。

转载于:https://www.cnblogs.com/lenve/p/4770532.html

android开发之Parcelable使用详解相关推荐

  1. android中oncreate方法,android开发之onCreate( )方法详解

    这里我们只关注一句话:This is where you should do all of your normal static set up.其中我们只关注normal static, normal ...

  2. android开发之onCreate( )方法详解

    android开发之onCreate( )方法详解 onCreate( )方法是android应用程序中最常见的方法之一,那么,我们在使用onCreate()方法的时候应该注意哪些问题呢? 先看看Go ...

  3. Android开发之EditText属性详解+++ImageView的属性

    Button的使用 不要阴影Button ---> TextView   (5.0新特性) <!-- 去按钮立体效果 --> <item name="android: ...

  4. Android 开发之EditText属性详解

    EditText & TextView 属性详解: android:layout_gravity="center_vertical" 设置控件显示的位置:默认top. an ...

  5. Android开发之CoordinatorLayout使用详解一

    2019独角兽企业重金招聘Python工程师标准>>> 主页:http://cherylgood.cn/20170302/51 官网描述为:CoordinatorLayout是一个增 ...

  6. Android快速开发之appBase——(4).详解com.snicesoft.Application和BaseActivity

    转载请注明本文出自JFlex的博客http://blog.csdn.net/jflex/article/details/46441571,请尊重他人的辛勤劳动成果,谢谢! Android快速开发之ap ...

  7. android idata 模式,Android快速开发之appBase——(3).详解IHolder和IData

    Android快速开发之appBase--(3).详解IHolder和IData IHolder和IData是AVLib的两个组件,在前面已经使用过了,那么这一篇将会详细说明这两个组件的用法. IHo ...

  8. iOS开发之Accounts框架详解

    2019独角兽企业重金招聘Python工程师标准>>> iOS开发之Accounts框架详解 Accounts框架是iOS原生提供的一套账户管理框架,其支持Facebook,新浪微博 ...

  9. 安卓开发之IPC机制详解

    IPC(Inter-Process Communication),意为进程间通信或者跨进程通信,是指两个进程之间进行数据交换的过程.前面在学习Handler机制时提到过线程与进程的概念,在安卓中一个进 ...

最新文章

  1. 也论标准: 统一是啥好事情?
  2. java swing 获取text_如何在Java Swing中将文本文件读入jtextarea
  3. spoj 26130 Binary numbers
  4. Vue 用户管理后台思维导图
  5. 【ArcGIS遇上Python】ArcGIS10.8 Python代码批量完美实现MODIS NDVI数据格式转换和投影变换
  6. SpringCloud Ribbon(六)之服务实例过滤器ServerListFilter
  7. 【指标需求思考】如何做好指标类需求建设
  8. 组装服务器配置清单_2020年组装电脑配置清单列表
  9. PX4 的 ECL EKF 公式推导及代码解析
  10. 通讯录c语言以文本文件保存,学C三个月了,学了文件,用C语言写了个通讯录程序...
  11. 持续集成部署Jenkins工作笔记0019---19.在Jenkins中指定Git客户端位置
  12. 爬取糗事百科1到5页的图片并下载到本地
  13. 去掉Eclipse插件Aptana启动显示My Aptana
  14. 如何朴实无华的双开微信?
  15. 5G China unicom AP:B SMS ASCII 转码要求
  16. BUGKU-成绩查询
  17. php deel views,视图(views)
  18. 人工智能如何改变新闻工作?
  19. oneAPI 、DPC++ 学习篇章
  20. RationalDMIS 2020 组合元素(元素定义)

热门文章

  1. mysql建立联合索引,mysql建立唯一键,mysql如何解决重复记录联合索引
  2. Go 知识点(04)— 结构体字段转 json格式 tag 标签的作用
  3. 深入理解 Embedding层的本质
  4. Jeff Dean回顾谷歌2021
  5. Tensor Core技术解析(上)
  6. 2021年大数据基础(三):​​​​​​​​​​​​​​​​​​​​​大数据应用场景
  7. oracle查看数据库字符编码,oracle 查看、批改字符集编码
  8. No view found for id 0x7f0900d8
  9. android R文件丢失解决方法
  10. Android SDK Manager 的介绍