0

我的问题很简单,但我无法应付他。我的设计中有计时器字段。

我想通过恢复屏幕来保存它们以避免失去时间价值(重新创建新活动)

我用来保存

    public Object onRetainConfigurationInstance(){
    return timeSeconds;
}

并重新建立timeSeconds = (Chronometer) getLastNonConfigurationInstance();

但它不起作用。有人可以帮我吗?我必须保存什么参数才能重新建立计时器时间?

4

2 回答 2

2
protected void onSaveInstanceState(Bundle outState) {
    outState.putLong(TIME_KEY, timeSeconds.getBase());
    super.onSaveInstanceState(outState);
}

protected void onRestoreInstanceState(Bundle savedInstanceState){
    if((savedInstanceState !=null)
            && savedInstanceState.containsKey(TIME_KEY)){
        timeSeconds.setBase(savedInstanceState.getLong(TIME_KEY));
    }
    super.onRestoreInstanceState(savedInstanceState);
}
于 2013-04-01T20:42:34.083 回答
1

您可能应该使用onSaveInstanceState()在方向更改之间保存数据,您的代码可能如下所示:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putLong("time_seconds", timeSeconds);
    super.onSaveInstanceState(outState);
}

然后你可以在 中获取存储的值,当方向改变时onCreate(),这被称为重新创建:Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    long timeSeconds = savedInstanceState.getLong("time_seconds");
    // other code from onCreate()
}
于 2013-03-31T19:43:36.553 回答