gpt4 book ai didi

android - 保存和恢复 View 状态android

转载 作者:IT老高 更新时间:2023-10-28 21:53:09 27 4
gpt4 key购买 nike

我知道 Activity 状态的保存和恢复。但我想做的是保存和恢复 View 的状态。我有一个自定义 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;
}

我希望这可以无缝运行,但遇到了错误:

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)

但这个 View 是我 Activity 中唯一的一个。所以,我问:

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

最佳答案

您删除 super.OnSaveInstanceState() 的结果并返回您自己的结果。然后稍后在 OnRestoreInstanceState(Parcelable) 返回您创建的那个。

解决方案在这里:

How to prevent custom views from losing state across screen orientation changes #2

关于android - 保存和恢复 View 状态android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6045361/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com