如何使自定义对象可拆分?
我正在尝试使我的对象可包裹。但是,我有自定义对象,这些对象具有ArrayList我制作的其他自定义对象的属性。
最好的方法是什么?
-
您可以在此处,此处(在此处获取代码)和此处找到一些示例。
您可以为此创建一个POJO类,但是您需要添加一些额外的代码来实现它Parcelable。看一下实现。
public class Student implements Parcelable{ private String id; private String name; private String grade; // Constructor public Student(String id, String name, String grade){ this.id = id; this.name = name; this.grade = grade; } // Getter and setter methods ......... ......... // Parcelling part public Student(Parcel in){ String[] data = new String[3]; in.readStringArray(data); // the order needs to be the same as in writeToParcel() method this.id = data[0]; this.name = data[1]; this.grade = data[2]; } @Оverride public int describeContents(){ return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(new String[] {this.id, this.name, this.grade}); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Student createFromParcel(Parcel in) { return new Student(in); } public Student[] newArray(int size) { return new Student[size]; } }; }
创建此类后,您可以Intent像这样轻松地传递此类的对象,并在目标活动中恢复该对象。
intent.putExtra("student", new Student("1","Mike","6"));
在这里,学生是从包中取消打包数据所需的密钥。
Bundle data = getIntent().getExtras(); Student student = (Student) data.getParcelable("student");
本示例仅显示String类型。但是,您可以打包任何所需的数据。试试看。