保存和恢复视图状态android

问题描述:

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

@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)

但这种观点在我的活动唯一的一个。所以,我问:

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

+0

我不得不因为Android的的设计多么可笑的笑。该方法不期望显示状态***显然***,它***显然***期望名为*** Parcelable ***的接口。是的,我们确实返回一个有效的*** Parcelable ***,它由*** Bundle ***实施。但是由于荒谬的原因失败了。我从来没有在.NET中遇到过这种设计,当它期望一个接口时,如果我们返回确切的接口,就不应该有任何异常。例外情况应该说更有意义的东西=)))Android是***糟糕的设计可以让你恼火的一个很好的例子。 – 2016-10-12 02:41:01

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

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

否则你失去超类保存的所有东西。

+4

onSaveInstanceState的默认实现返回null。另外,这里的捆绑包是Parcelable,它没有任何像putInt这样的方法。 – 2011-05-18 14:45:32

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

该解决方案是在这里:

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

+1

你不会放弃结果 - 你的祖先可能已经保存了状态,然后你会以错误的顺序读出输入 – ataulm 2014-05-12 16:06:22