我有一个扩展FragmentActivity的简单类。我使用getLastCustomNonConfigurationInstance / onRetainCustomNonConfigurationInstance来保存当前状态。
public class MyActivity extends FragmentActivity {
static class Saver {
// ...
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Saver saver = (Saver) getLastCustomNonConfigurationInstance();
if (saver != null) {
// ...
}
// ...
}
@Override
public Object onRetainCustomNonConfigurationInstance() {
Saver saver = new Saver();
// ...
return saver;
}
}
当我关闭此活动时,我偶尔会遇到一个奇怪的异常,例如:
java.lang.ClassCastException: Saver cannot be cast to android.support.v4.app.FragmentActivity$NonConfigurationInstances
at android.support.v4.app.FragmentActivity.getLastCustomNonConfigurationInstance(FragmentActivity.java:576)
...
您如何看待这个问题?提前谢谢!
答案 0 :(得分:3)
你需要像这样进行演员表:
Object saver = getLastCustomNonConfigurationInstance();
if (saver != null) {
Saver savedObject = (Saver)saver;
}