要将对象的数组列表传递给片段,我必须使列表对象可以使用。
public mObjectClass implements Parcelable {
// Some code
}
问题是我的列表对象中的一个属性是另一个基于对象的arrayList。
public mObjectClass implements Parcelable {
// Some code
private ArrayList<someOtherObject> anotherArrayList;
}
如何使mObjectClass变得可分割?
答案 0 :(得分:1)
someOtherObject
必须实施Parcelable
(在您的问题中不会扩展)。然后,您可以调用parcel.writeTypedList(anotherArrayList);
来编写它,然后parcel.readTypedList(yourList, someOtherObject.CREATOR)
将其读回来。您可以阅读更多here
答案 1 :(得分:0)
此解决方案受到一些Stackoverflow帖子的严重影响,包括 this
基本上使两个类都可以使用parcelable.Creator。
mObjectClass:
public class mObjectClass implements Parcelable {
private ArrayList<someOtherObject> anotherArrayList;
//add getter + setter...
public mObjectClass() {
anotherArrayList = new ArrayList<someOtherObject>();
}
public mObjectClass(Parcel in) {
anotherArrayList = new ArrayList<someOtherObject>();
in.readTypedList(anotherArrayList, someOtherObject.CREATOR);
}
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel outParcel, int flags) {
outParcel.writeTypedList(anotherArrayList);
}
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
@Override
public mObjectClass createFromParcel(Parcel in) {
return new mObjectClass(in);
}
@Override
public mObjectClass[] newArray(int size) {
return new mObjectClass[size];
}
};
}
someOtherObject:
public class someOtherObject implements Parcelable {
String someString;
//add getter + setter...
public void writeToParcel(Parcel out, int flags) {
out.writeString(someString);
}
public static final Parcelable.Creator<someOtherObject> CREATOR = new Parcelable.Creator<someOtherObject>() {
public someOtherObject createFromParcel(Parcel in) {
return new someOtherObject(in);
}
public someOtherObject[] newArray(int size) {
return new someOtherObject[size];
}
};
public int describeContents() {
return 0;
}
public someOtherObject(Parcel in) {
someString = in.readString();
}
public someOtherObject() {
}
public someOtherObject(String someString) {
this.someString = someString;
}
}
Tada,您现在可以在初始化之后添加mObjectClass作为额外内容,并使用setter将Arraylist与其他someOtherObjects一起设置。