码迷,mamicode.com
首页 > 其他好文 > 详细

通过Intent传递对象的两种方法

时间:2015-01-27 00:21:07      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

1 Serializable

2 Parcelable 

实现方法:

a.定义两个javaBean(Book,Person),分别implements SerializableParcelable

b.建立Activity,用来传递Object对象和接收Object对象,通过SerializeablePacelable方法传递对象,分别调用方法

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);

1.Serializable 

定义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);

2.Parcelable

定义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接口必须有一个staticCREATOR对象,这个对象实现Parcelable.Creator接口

 

通过Intent传递对象的两种方法

标签:

原文地址:http://www.cnblogs.com/liyuejiao/p/4251673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!