我的问题很简单,但我不能和他打交道。 我的设计中有天文台字段。
我想保存它们以避免因恢复屏幕而丢失时间(重新创建新活动)
我用于保存
public Object onRetainConfigurationInstance(){
return timeSeconds;
}
重新建立timeSeconds = (Chronometer) getLastNonConfigurationInstance();
但它不起作用。有人能帮帮我吗?我必须保存哪些参数才能重新建立计时器时间?
答案 0 :(得分: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);
}
答案 1 :(得分: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()
}