android开发之Parcelable使用详解
想要在两个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即可
*/
@Override
public int describeContents() {
return 0;
}
/**
* 把值写入Parcel中
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(username);
dest.writeString(nickname);
dest.writeInt(age);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
/**
* 供外部类反序列化本类数组使用
*/
@Override
public Person[] newArray(int size) {
return new Person[size];
}
/**
* 从Parcel中读取数据
*/
@Override
public 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<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();
* }
* }</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);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。
android开发之Parcelable使用详解的更多相关文章
- [置顶] Android开发之MediaPlayerService服务详解(一)
前面一节我们分析了Binder通信相关的两个重要类:ProcessState 和 IPCThreadState.ProcessState负责打开Binder 驱动,每个进程只有一个.而 IPCThre ...
- Android开发之EditText属性详解
1.EditText输入的文字为密码形式的设置 (1)通过.xml里设置: 把该EditText设为:android:password="true" // 以”.”形式显示文本 ( ...
- 【转】 Android开发之EditText属性详解
原文网址:http://blog.csdn.net/qq435757399/article/details/7947862 1.EditText输入的文字为密码形式的设置 (1)通过.xml里设置: ...
- android开发之onCreate( )方法详解
这里我们只关注一句话:This is where you should do all of your normal static set up.其中我们只关注normal static,normal: ...
- Android开发之MediaRecorder类详解
MediaRecorder类介绍: MediaRecorder类是Android sdk提供的一个专门用于音视频录制,一般利用手机麦克风采集音频,摄像头采集图片信息. MediaRecorder主要函 ...
- android开发之PreferenceScreen使用详解
是在惭愧,学习android也有一段时间了,今天才是第一次接触PreferenceScreen.记录下来,与大家分享. 本文参考:http://lovezhou.iteye.com/blog/1020 ...
- Android开发之SoundPool使用详解
使用SoundPool播放音效 如果应用程序经常播放密集.急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了.因为MediaPlayer存在如下缺点: 1) 延时时间较长 ...
- NDK开发之JNIEnv参数详解
即使我们Java层的函数没有参数,原生方法还是自带了两个参数,其中第一个参数就是JNIEnv. 如下: native方法: public native String stringFromC(); pu ...
- NDK开发之ndk-build命令详解
毫无疑问,通过执行ndk-build脚本启动android ndk构建系统. 默认情况下,ndk-build脚本在工程的主目录中执行,如: 我们可以用使用-C参数改变上述行为,-C指定工程的目录,这样 ...
随机推荐
- Introduction to Gaussian Processes
Introduction to Gaussian Processes Gaussian processes (GP) are a cornerstone of modern machine learn ...
- 【HDU 4436】 str2int (广义SAM)
str2int Problem Description In this problem, you are given several strings that contain only digits ...
- windows 挂载windows 共享盘为本地磁盘
我们在设置数据库自动备份时,为了数据的安全往往需要直接将数据备份到远程服务器上.在Linux可以通过NFS挂载来实现,在Windows平台可以直接通过net use+subst来实现将远程服务器的目录 ...
- 轻松学习RSA加密算法原理 (转)
轻松学习RSA加密算法原理 (转) http://blog.csdn.net/q376420785/article/details/8557266 http://www.ruanyifeng.com/ ...
- jboss项目迁移至WebLogic12
1 weblogic 使用jtds-1.2.3.jar驱动链接MS SQL Server 2008的数据源配置 1.1 拷贝jtds-1.2.3.jar至D:\Oracle\Middleware\wl ...
- Mac 下配置XAMPP
1:去官方下载 2:安装dmg 3:安装完成后, 网页上提示, 要设置相应的密码, 设置完成. 4:打开对应的app程序, 把 mysql Database运行起来, 不然, 网页上看到的就是未运行状 ...
- java基础(十六)集合(三)
这里有我之前上课总结的一些知识点以及代码大部分是老师讲的笔记 个人认为是非常好的,,也是比较经典的内容,真诚的希望这些对于那些想学习的人有所帮助! 由于代码是分模块的上传非常的不便.也比较多,讲的也是 ...
- ManagerDay-1
初做管理,没有任何管理经验的我,有点紧张,在来公司之前,脑子里一直在想能不能胜任这份工作. 想着能否做出合格的流程图,像样的需规.我该如何和组内开发人员打好交道.报价预算该如何做,这些都交织在脑内显得 ...
- FireMonkey隐藏任务栏图标
FMX(FireMonkey)可以轻松实现很多VCL无法或难以实现的特效,所以将FMX程序作为界面,打包入DLL由VCL程序调用,是一个不错的方案.为了程序的完整性,你不想看见FMX程序在任务栏上显示 ...
- 理解wait notify的好例子
import java.util.concurrent.TimeUnit; public class Example2 { /** * @param args */ public static voi ...