你需要创建你的Book
类Parcelable
,然后你可以将它作为Parcelable
数组传递Bundle
给并直接从Bundle
.
查看简单的 Parcelable 示例
假设你的代码
public class Book implements Parcelable{
private String id;
private String title;
private String authors;
private String isbn;
private String price;
// Constructor
public Student(String id, String title, String authors,String isbn,String price){
this.id = id;
this.title= title;
this.authors = authors;
this.isbn=isbn;
this.price=price;
}
......................................
// Parcelling part
public Book(Parcel in){
String[] data = new String[5];
in.readStringArray(data);
this.id = data[0];
this.title= data[1];
this.authors= data[2];
this.isbn= data[3];
this.price= data[4];
}
@Оverride
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.title,
this.authors,this.isbn,this.price});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Book createFromParcel(Parcel in) {
return new Book(in);
}
public Book[] newArray(int size) {
return new Book[size];
}
};
}
现在创建 Parcelable 类后,您可以传递如下数据:
resultIntent.putExtra(BOOK_RESULT_KEY,new Book(id, title.getText().toString(),authors , isbn.getText().toString(), "$9.99"));
从 Bundle 中获取数据如下:
Bundle data = getIntent().getExtras();
Book b = (Book)data.getParcelable(AddBookActivity.BOOK_RESULT_KEY);