保存和恢复视图状态android

Vla*_*nov 30 android bundle view

我知道活动状态保存和恢复.但我想要做的是保存和恢复视图的状态.我有一个自定义视图和两个重写方法:

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        currentLeftX = bundle.getInt(CURRENT_LEFT_X_PARAM, 0);
        currentTopY = bundle.getInt(CURRENT_TOP_Y_PARAM, 0);
    }
    super.onRestoreInstanceState(state);
}

@Override
protected Parcelable onSaveInstanceState() {
    super.onSaveInstanceState();
    Bundle bundle = new Bundle();
    bundle.putInt(CURRENT_LEFT_X_PARAM, currentLeftX);
    bundle.putInt(CURRENT_TOP_Y_PARAM, currentTopY);
    return bundle;
}
Run Code Online (Sandbox Code Playgroud)

我希望这可以无缝工作,但遇到并且错误:

引起:java.lang.IllegalArgumentException:错误的状态类,期待View State但是收到类android.os.Bundle.当两个不同类型的视图在同一层次结构中具有相同的id时,通常会发生这种情况.该视图的id是id/mapViewId.确保其他视图不使用相同的ID.在android.view.View.onRestoreInstanceState(View.java:6161)

但这种观点是我活动中唯一的观点.所以,我问:

保存视图状态的正确方法是什么?

dmo*_*mon -4

我可能是错的,但我认为你需要保存父返回的包:

@Override
protected Parcelable onSaveInstanceState() {
    Parcelable bundle = super.onSaveInstanceState();
    bundle.putInt(CURRENT_LEFT_X_PARAM, currentLeftX);
    bundle.putInt(CURRENT_TOP_Y_PARAM, currentTopY);
    return bundle;
}
Run Code Online (Sandbox Code Playgroud)

否则你将失去超类保存的一切。

  • onSaveInstanceState 的默认实现返回 null。另外,这里的bundle是Parcelable,它没有像putInt这样的方法。 (4认同)