android Parcelable类
来源:互联网 发布:安卓 java webservice 编辑:程序博客网 时间:2024/05/22 14:51
android Parcelable类表示该类可以用来序列化,打包为数据流对象Parcel,通常用于进程间通信传递自定义数据类型。
Parcel也相应的提供了一系列write/get方法方便打包和解包Parcel类。
需要实现的方法主要是如何打包和解包Parcel类,具体如下:
/** * 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);
在此方法中,需要将当前类需要保存的数据用Parcel.write*方法写入dest中,打包为Parcel对象。
同时在当前类中也需要定义一个全局static final常量CREATOR,同时实现其中的解包Parcel的方法
/** * 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); }
import android.os.Parcel;import android.os.Parcelable;public class Book implements Parcelable{ private String name; private int count; @Override public int describeContents() { return 0; } // write all parameters to parcel @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(count); } public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() { @Override public Book createFromParcel(Parcel source) { Book book = new Book(); book.name = source.readString(); book.count = source.readInt(); return book; } @Override public Book[] newArray(int size) { return new Book[size]; } };}
需要注意的是打包/解包时数据应该尽量一致,即wirteToParcel和createFromParcel中读写的顺序应该一致。
0 0
- android Parcelable类
- android实体类的Parcelable
- Android Parcelable实现类混淆
- Android Parcelable
- Android Parcelable
- Android Parcelable
- Android Parcelable
- Android Parcelable
- android parcelable
- android Parcelable
- android Parcelable
- Android Parcelable
- Android Parcelable
- Android Parcelable
- Android :Parcelable
- android Parcelable
- Android Parcelable
- Android Parcelable
- 《按比例显示图片》listview 加载网络图片 用ImageLoader.display listview_item中上下有留白现象
- 在VirtualBox Ubuntu虚拟机上安装GAMIT-GLOBK
- 淘宝内部分享:怎么跳出MySQL的10个大坑
- LeetCode Merge Sorted Array
- Unable to get package info for com.example.sampletest; is package not installed?
- android Parcelable类
- kettle —— 字段剪裁,数据去重,js转换
- 通用makefile
- 不安装oracle客户端,使用navicat、pl/sql developer连接oracle数据库
- flume+kafka+storm+mysql 数据流
- C++二叉树遍历递归与栈循环的实现
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料
- 教训
- JavaScript日期函数汇集12个