onRestoreInstanceState () не вызывается при изменении вращения - PullRequest
0 голосов
/ 24 марта 2020

У меня есть холст, на котором я рисую прямоугольники, и я хочу, чтобы эти поля сохранялись и снова отображались после изменения конфигурации - в моем случае поворот экрана.

Проблема, которая, как мне кажется, у меня возникает, заключается в том, что 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);
    }
}

1 Ответ

0 голосов
/ 24 марта 2020

Вы должны посмотреть на это do c

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));
}
...