以下是我的课程:
public class Line implements Parcelable {
private Point start, end;
public Line() {
// TODO Auto-generated constructor stub
}
public Line(Point start, Point end) {
this.end = end;
this.start = start;
}
public Point getStart() {
return start;
}
public void setStart(Point start) {
this.start = start;
}
public Point getEnd() {
return end;
}
public void setEnd(Point end) {
this.end = end;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
它包含两个Point(android.graphics.Point
)对象,我想在其中实现parcelable,以便我可以在Line
中恢复Activity
个对象的ArrayList。
问题是因为我的两个属性都是Point类型,不确定如何在writeToParcel
中编写它并在
public Line(Parcel in) {
super();
}
修改
在答案后我实现了Line类。但在活动中,问题是onRestoreInstanceState
永远不会被调用。
当我按下主页按钮,然后返回应用程序时,我的数组列表中的所有数据都将丢失。
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putInt("player", player);
savedInstanceState.putParcelableArrayList("lines", lines);
savedInstanceState.putParcelableArrayList("rects1", rects1);
savedInstanceState.putParcelableArrayList("rects2", rects2);
// etc.
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
player = savedInstanceState.getInt("player");
lines = savedInstanceState.getParcelableArrayList("lines");
rects1 = savedInstanceState.getParcelableArrayList("rects1");
rects2 = savedInstanceState.getParcelableArrayList("rects2");
}
答案 0 :(得分:1)
试试这个......
public class Line implements Parcelable {
private Point start, end;
public Line() {
}
public Line(Point start, Point end) {
this.end = end;
this.start = start;
}
public Point getStart() {
return start;
}
public void setStart(Point start) {
this.start = start;
}
public Point getEnd() {
return end;
}
public void setEnd(Point end) {
this.end = end;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(start, flags);
dest.writeParcelable(end, flags);
}
@Override
public int describeContents() {
return 0xDEAF;
}
public static final Parcelable.Creator<Line> CREATOR = new Parcelable.Creator<Line>() {
@Override
public Line createFromParcel(Parcel source) {
Line line = new Line();
Point start = source.readParcelable(Point.class.getClassLoader());
Point end = source.readParcelable(Point.class.getClassLoader());
line.setStart(start);
line.setEnd(end);
return line;
}
@Override
public Line[] newArray(int size) {
return new Line[size];
}
};
}
答案 1 :(得分:0)
使用我的Answer。 您需要在writeToParcel方法中写入所有值。 并创建一个构造函数并执行以下步骤。