今天要給大家講一下Android中Intent中如何傳遞對象,就我目前所知道的有兩種方法,一種是Bundle.putSerializable(Key,Object);另一種是Bundle.putParcelable(Key, Object);當然這些Object是有一定的條件的,前者是實現了Serializable接口,而後者是實現了Parcelable接口,為了讓大家更容易理解我還是照常寫了一個簡單的Demo,大家就一步一步跟我來吧!
第一步:新建一個Android工程命名為ObjectTranDemo(類比較多哦!)目錄結構如下圖:
第二步:修改main.xml布局文件(這裡我增加了兩個按鈕)代碼如下
[java]
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Welcome to Mr wei's blog."
- />
- <Button
- android:id="@+id/button1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Serializable"
- />
- <Button
- android:id="@+id/button2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Parcelable"
- />
- </LinearLayout>
第三步:新建兩個類一個是Person.java實現Serializable接口,另一個Book.java實現Parcelable接口,代碼分別如下:
Person.java:
[java]
- package com.tutor.objecttran;
- import java.io.Serializable;
- 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;
- }
-
- }
Book.java:
[javascript]
- package com.tutor.objecttran;
- import android.os.Parcel;
- import android.os.Parcelable;
- 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);
- }
- }