计时器在更改方向上重新启动

时间:2016-05-13 05:45:55

标签: java android orientation chronometer

我改变方向时重置计时器值,写的是真的,但没有帮助,请求帮助,出了什么问题

@Override
protected void onSaveInstanceState(Bundle outState) {
timer = SystemClock.elapsedRealtime() - chronometer.getBase();
outState.putLong("timerValue", timer);
super.onSaveInstanceState(outState);
}

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.details_layout);

chronometer = (Chronometer) findViewById(R.id.chronometer);
chronometer.setBase(SystemClock.elapsedRealtime());
if (savedInstanceState != null) {
    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        public void onChronometerTick(Chronometer chronometer) {
            timer = savedInstanceState.getLong("timerValue");
            chronometer.setText(DateFormat.format("mm:ss", timer));
        }
    });
    chronometer.start();
} else {
    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        public void onChronometerTick(Chronometer chronometer) {
            timer = SystemClock.elapsedRealtime() - chronometer.getBase();
            chronometer.setText(DateFormat.format("mm:ss", timer));
        }
    });
    chronometer.start();
}
}

1 个答案:

答案 0 :(得分:0)

警告:每次用户旋转屏幕时,您的活动都将被销毁并重新创建。当屏幕更改方向时,系统会破坏并重新创建前台活动,因为屏幕配置已更改,您的活动可能需要加载其他资源(例如布局)。

请参阅: How to contain value of android chronometer with change in orientation