保存和恢复视图状态android [英] Saving and restoring view state android
问题描述
我知道活动状态的保存和恢复.但我想要做的是保存和恢复视图的状态.我有一个自定义视图和两个覆盖的方法:
I'm aware of activity state saving and restoring. But what I want to do is saving and restoring the state of a view. I have a custom view and two overrided methods in it:
@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;
}
我希望这能无缝运行,但遇到错误:
I expected this to work seamless, but encountered and error:
原因:java.lang.IllegalArgumentException:错误的状态类,期待查看状态但接受类android.os.Bundle 代替.这通常发生在两种观点时不同的类型在相同的层次结构.这个视图的 id 是id/mapViewId.确保其他视图可以不使用相同的ID.在 android.view.View.onRestoreInstanceState(View.java:6161)
Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.os.Bundle instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/mapViewId. Make sure other views do not use the same id. at android.view.View.onRestoreInstanceState(View.java:6161)
但是这个视图是我活动中唯一的一个.所以,我问:
But this view is the only one in my activity. So, I'm asking:
保存视图状态的正确方法是什么?
What is the right way to save the state of the view?
推荐答案
您删除 super.OnSaveInstanceState()
的结果并返回您自己的结果.然后在 OnRestoreInstanceState(Parcelable)
返回你创建的那个.
You drop the result of super.OnSaveInstanceState()
and return your own.
Then later at OnRestoreInstanceState(Parcelable)
you return the one which you created.
解决方案在这里:
这篇关于保存和恢复视图状态android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!