Activity之间通过Intent传递值,支持基本数据类型和String对象及它们的数组对象byte、byte[]、char、char[]、boolean、boolean[]、short、short[]、int、int[]、long、long[]、float、float[]、double、double[]、String、String[],还有采用实现Serializable、Parcelable接口的类对象传递数据的两种方法:一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key, Object)
例如:
- 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);
- }
- }
实现Serializable接口:
- 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;
- }
- }
这样在Activity中就可编写传递数据代码:
- Intent mIntent = new Intent(this, 地址Activity.class);
- Bundle mBundle = new Bundle();
- //采用parcelable传输数据
- mBundle.putParcelable("data", mBook);
- //采用serializable传输数据
- mBundle.putSerializable("data", items);
- mIntent.putExtras(mBundle);
- startActivity(mIntent);
接受数据可以采用:
- Intent intent = getIntent();
- ArrayList<Map<String, String>> items = (ArrayList<Map<String, String>>)intent.getExtras().get("data");