本次记录要理解为什么实现Parcelable 接口 就能在 安卓 组件之间传递数据, 其实 Parcelable 仅仅是一个接口, 它本身并不具备传递数据的功能,真正在组件之间传递数据的是 Parcel类. 查看 Parcel 的 源码, 可以看到 此类 里面 调用 native 方法 对 各种基本类型的数据进行 封装处理 , 将数据传递到 C/C++ 所在系统底层 进行传输的。
知道这些 有助 于 理解 Parcelable 接口。
实现 Parcelable 接口里 需要实现 它的一个 内部泛型接口,其源码如下:
源码开始:
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);
}
源码结束
使用实例
public class Book implements Parcelable
{
private String bookName;
private String author;
private int publishDate;
public Book()
{
}
public String getBookName()
{
return bookName;
}
public void setBookName(String bookName)
{
this.bookName = bookName;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public int getPublishDate()
{
return publishDate;
}
public void setPublishDate(int publishDate)
{
this.publishDate = publishDate;
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags)
{
out.writeString(bookName);
out.writeString(author);
out.writeInt(publishDate);
}
public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>()
{
@Override
public Book[] newArray(int size)
{
return new Book[size];
}
@Override
public Book createFromParcel(Parcel in)
{
return new Book(in);
}
};
public Book(Parcel in)
{
bookName = in.readString();
author = in.readString();
publishDate = in.readInt();
}
}