1

我有一个扩展 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)
...

你怎么看这个问题?提前致谢!

4

1 回答 1

3

您需要像这样进行演员表:

Object saver = getLastCustomNonConfigurationInstance();
if (saver != null) {
    Saver savedObject = (Saver)saver;
} 
于 2012-10-19T09:27:22.647 回答