标签:
1 Serializable
2 Parcelable
实现方法:
a.定义两个javaBean(Book,Person),分别implements Serializable和Parcelable
b.建立Activity,用来传递Object对象和接收Object对象,通过Serializeable和Pacelable方法传递对象,分别调用方法
bundle.putSerializable(String key,Serializable value)
bundle.putParcelable(String key,Parcelable value)
c.根据key接收通过Intent传递的Object对象
Person mPerson = (Person) getIntent().getSerializableExtra(IntentObject.SER_KEY);
Book mBook = (Book)getIntent().getParcelableExtra(IntentObject.PAR_KEY);
定义javaBean(Person),实现Serializable接口
public class Person implements Serializable {
private String name;
private int age;
//get,set方法
}
在Activity中调用:
public void SerializeMethod() {
Person mPerson = new Person();
mPerson.setName("frankie");
mPerson.setAge(25);
Intent mIntent = new Intent(this, ReceiveObjectFromSerialize.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable(SER_KEY, mPerson);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
在另一个Activity接收:
Person mPerson = (Person) getIntent().getSerializableExtra(IntentObject.SER_KEY);
定义javaBean(Book)实现Parcelable接口
public class Book implements Parcelable {
private String bookName;
private String author;
private int publishTime;
//get,set方法
... ...
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);
}
在Activity中调用:
public void PacelableMethod() {
Book mBook = new Book();
mBook.setBookName("Android Tutor");
mBook.setAuthor("Frankie");
mBook.setPublishTime(2010);
Intent mIntent = new Intent(this, ReceiveObjectFromParcel.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(PAR_KEY, mBook);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
在另一个Activity中接收:
Book mBook = (Book)getIntent().getParcelableExtra(IntentObject.PAR_KEY);
*官网说明:
类实现Parcelable接口必须有一个static的CREATOR对象,这个对象实现Parcelable.Creator接口
标签:
原文地址:http://www.cnblogs.com/liyuejiao/p/4251673.html