问题描述
我试图让我的对象是Parcelable。不过,我有自定义的对象和这些对象有我做了其他自定义对象的ArrayList属性。
I'm trying to make my objects be Parcelable. However, I have custom objects and those objects have arraylist attributes of other custom objects I have made.
什么是我能做到这一点的最好方法是什么?
What would be the best way I could do this?
推荐答案
您可以找到一些这方面的例子的,这里(code被带至此处),。
You can find some examples of this here, here (code is taken here), .
您可以创建一个POJO类,但你需要添加一些额外的code,使其Parcelable。看一看执行。
You can create a POJO class for this, but you need to add some extra code to make it Parcelable. Have a look at the implementation.
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);
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];
}
};
}
一旦你创建了这个类,你可以很容易地通过这样的意图通过这个类的对象,并在目标活动中恢复这个对象。
Once you have created this class, you can easily pass objects of this class through the Intent like this, and recover this object in the target activity.
intent.putExtra("student", new Student("1","Mike","6"));
下面,学生,你将需要从束unparcel的数据的密钥。
Here, the student is the key which you would require to unparcel the data from the bundle.
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
这个例子只显示字符串类型。但是,你可以包裹你想要的任何类型的数据。试试吧。
This example shows only String types. But, you can parcel any kind of data you want. Try it out.
编辑:另一个例如,通过Rukmal迪亚斯建议
Another example, suggested by Rukmal Dias.
这篇关于我怎样才能让我的自定义对象是Parcelable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!