Android Chronometer starts and stops but carries o

2019-07-17 04:49发布

问题:

I've created an app that has a toggle button to start and stop a Chronometer, like a stop watch. When you first press the toggle button (executes .start()), the chronometer will start counting, when you then press the button again (executes .stop()), the chronometer appears on screen to stop counting as it should but when it is then started again it shows that it's actually still been counting in the background and shows the time on screen as if it was never stopped

code:

tglStartStop.setOnCheckedChangeListener(new OnCheckedChangeListener(){

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {

            if (tglStartStop.isChecked()) {

                chronStopwatch.start();
            }

            else {

                chronStopwatch.stop();
            }

        }

    });

回答1:

Add this line before "chronStopwatch.start();"

chronStopwatch.setBase(SystemClock.elapsedRealtime());