我制作了一个可以绘制的自定义视图,并将该图形保存到arraylist中。我想将这些数组列表保存在onSaveInstanceState中,并在onRestoreInstanceState中检索它们。我已经尝试过将Sharedpreferences与Json结合使用,但它无法正常工作甚至无法打包。我要保存路径和绘画。
笔类:
private static class Pen implements Parcelable {
Path path;
Paint paint;
int color;
float width;
Pen(int colort, float widtht ) {
color = colort;
width = widtht;
path = new Path();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(width);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
// De-parcel Pen object
public Pen(Parcel in) {
color = in.readInt();
width = in.readFloat();
path = new Path();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(width);
paint.setColor(color);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
}
// Function that writes Dice values to parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(color);
dest.writeFloat(width);
}
// Creator of Parcelable
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Pen createFromParcel(Parcel in) {
return new Pen(in);
}
public Pen[] newArray(int size) {
return new Pen[size];
}
};
// Function to implement Parcelable interface
@Override
public int describeContents() {
return 0;
}
}
OnsaveInstanceState:
@Override
public Parcelable onSaveInstanceState()
{
Bundle bundle = new Bundle();
bundle.putParcelable("superState", super.onSaveInstanceState());
bundle.putParcelableArrayList("pen", mPenList);
return bundle;
}
onRestoreInstanceState:
@Override
public void onRestoreInstanceState(Parcelable state)
{
if (state instanceof Bundle) // implicit null check
{
Bundle bundle = (Bundle) state;
this.mPenList = bundle.getParcelableArrayList("pen");
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
答案 0 :(得分:0)
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save the state so that next time we know if we need to refresh data.
outState.putParcelableArrayList("yourkey",yourlist);
);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
list= savedInstanceState.getParcelableArrayList("yourkey");
}
也许这可以帮助您:)