使自定义对象的ArrayList可以分组

我有两个类创build对象,我需要通过意图,我目前正在尝试实现Parcelable来做到这一点。

import android.os.Parcel; import android.os.Parcelable; public class Item implements Parcelable { private String name; private double price; private int buyerCount = 0; public Item(String name, double price) { this.name = name; this.price = price; } private Item(Parcel in) { name = in.readString(); price = in.readDouble(); } public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { public Item createFromParcel(Parcel in) { return new Item(in); } public Item[] newArray(int size) { return new Item[size]; } }; @Override public int describeContents() { return 0; } public double getPrice() { return price; } public int getBuyerCount() { return buyerCount; } public void incrementBuyerCount() { buyerCount += 1; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeDouble(price); } } 

从testing到目前为止,我的Item对象似乎正确地传递信息,当我捆绑它。

然而,我的第二个类Diner包含对象Item的ArrayList,我不确定如何在这个类中正确实现Parcelable,特别是在我已经评论的部分。 我看到有一个readParsableArray()方法,但没有ArrayLists。

 import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; public class Diner implements Parcelable { private String name; private ArrayList<Item> itemList = new ArrayList<Item>(); public Diner(String name) { this.name = name; } private Diner(Parcel in) { name = in.readString(); // How to read in ArrayList itemList of item objects? itemList = in.readParcelableArray(); } public static final Parcelable.Creator<Diner> CREATOR = new Parcelable.Creator<Diner>() { public Diner createFromParcel(Parcel in) { return new Diner(in); } public Diner[] newArray(int size) { return new Diner[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); // How to write ArrayList itemList of item objects? dest.writeParcelableArray(itemList); } public void addItem(Item foodItem) { itemList.add(foodItem); foodItem.incrementBuyerCount(); } public double getPrice() { double total = 0; for(Item item : itemList) { total += item.getPrice() / item.getBuyerCount(); } return total; } public String toString() { return name; } } 

Solutions Collecting From Web of "使自定义对象的ArrayList可以分组"