保存和恢复视图状态的android视图、状态、android

2023-09-04 06:23:39 作者:抱歉丶你不是我的唯一

我所知道的节能活动状态和恢复。 但我想要做的是保存和恢复视图状态。 我有它的自定义视图和两个overrided方式:

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是   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?

推荐答案

看看这样的回答:

How从整个屏幕方向失去状态prevent自定义视图改变