http://blog.youkuaiyun.com/xyz_lmn/article/details/5908355
Intent传递对象的方式有两种,一种是Bundle.putSerializable(key,Object);当然,这里的object是实现了Serializable接口的,另一种是Bundle.putPacelable(key,Object);这里的Object则是需要实现parcelable接口
Bundle.putSerializable(key,Object)
Object实现Serializable接口,需要生成一个SerialVersionUID,这个是有eclipse自动生成的long的id
- public class Person implements Serializable {
- private static final long serialVersionUID = -7060210544600464481L;
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
Bundle.putParcelable(key,Object);
Object实现接口Parcelable接口,要实现两个方法和一个接口,分别是
describContents();这个方法不用复写,直接返回0就可以了,具体为什么不清楚
writeToParcel(Parcle desc,int flags),Parcel的意思就是包裹,顾名思义,写到包里面去,参数为要写进去的包,还有一个flags开关,不清楚用来干嘛的,包desc里面提供了写的方法,
desc.writeString(),desc.writeInt(),写的时候虽然什么都没跟,但是应该是同过bean里面的字段,就是传进去的参数来做标记的
public static final Parcelable.create() CREATOR = new Parcelable.create()接口,名字一定要是CREATOR,里面有两个方法要实现,一个是写数组,一个是写对象,,将对象读出来
返回一个new T[]的数组
public
Person[] newArray(
int
size)
返回一个对象,CreateFromParcel,和writeToParcel对应
public
Person createFromParcel(Parcel source)
- public class Book implements Parcelable {
- private String bookName;
- private String author;
- private int publishTime;
- 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 getPublishTime() {
- return publishTime;
- }
- public void setPublishTime(int publishTime) {
- this.publishTime = publishTime;
- }
- public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
- public Book createFromParcel(Parcel source) {
- Book mBook = new Book();
- mBook.bookName = source.readString();
- mBook.author = source.readString();
- mBook.publishTime = source.readInt();
- return mBook;
- }
- public Book[] newArray(int size) {
- return new Book[size];
- }
- };
- public int describeContents() {
- return 0;
- }
- public void writeToParcel(Parcel parcel, int flags) {
- parcel.writeString(bookName);
- parcel.writeString(author);
- parcel.writeInt(publishTime);
- }
- }
传递数据的方式:
Serializable
Person p = new Person();
Intent intent = new Intent(this,Demo.class);
Bundle mbundle = new Bundle();
mbundle.putSerializable(key,p
);
intent.putExtirs(mbundle);
startActivity(intent);
获取
Person p = (Person)getIntent().getSerializableExtra(key);这里没有获取bundle是因为intent里面已经封装了Bundle,
-----------------------------------------------------------------------
Parcelable
Book b = new Book();
Intent intent = new Intent(this,Demo.class);
Bundle mbundle = new Bundle();
mbundle.putParcelable(key,b);
intent.putExtras(mbundle);
startActivity(intent);
获取
Book b = (Book)getIntent().getParcelableExtra(key);