有一个画布,我在那里画框,我希望这些框保存和显示后,配置更改-在我的情况下,屏幕旋转。
我认为我存在的问题是,即使活动被破坏和重新创建,onRestoreInstance()也不会在旋转时被调用。
我是否没有将数据正确地保存到包中?
自定义视图BoxDrawingView,我想保存我的状态,并在旋转后检索它。
public class BoxDrawingView extends View{
private Box mCurrentBox;
private ArrayList<Box> mBoxList = new ArrayList<>();
....
@Nullable
@Override
protected Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("superState", super.onSaveInstanceState());
bundle.putParcelableArrayList("listOfBoxes", mBoxList);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
print();
if(state instanceof Bundle){
Bundle bundle = (Bundle) state;
print();
this.mBoxList = (ArrayList<Box>)bundle.get("listOfBoxes");
print();
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
private void print(){
for(int i = 0; i < mBoxList.size(); i ++) {
Log.i(TAG, "Box #" + i);
}
}
....
}盒类
public class Box implements Parcelable {
private PointF mOrigin;
private PointF mCurrent;
public Box(PointF origin){
mOrigin = origin;
}
public PointF getOrigin() {
return mOrigin;
}
public PointF getCurrent() {
return mCurrent;
}
public void setCurrent(PointF current) {
mCurrent = current;
}
protected Box(Parcel in){
mOrigin = in.readParcelable(PointF.class.getClassLoader());
mCurrent = in.readParcelable(PointF.class.getClassLoader());
}
public static final Creator<Box> CREATOR = new Creator<Box>() {
@Override
public Box createFromParcel(Parcel in) {
return new Box(in);
}
@Override
public Box[] newArray(int size) {
return new Box[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(mOrigin, flags);
dest.writeParcelable(mCurrent, flags);
}
}发布于 2020-03-24 16:09:58
你应该看看这个文档
TL;DR
若要保存您,请使用:
// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(GAME_STATE_KEY, gameState);
outState.putString(TEXT_VIEW_KEY, textView.getText());
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}恢复:
// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}https://stackoverflow.com/questions/60834814
复制相似问题