javaandroidbuttonchronometer

Restart Chronometer on Button Click After Resetting


This is how i start the chronometer:

btnCount.setEnabled(true);

        if (!mIsStarted) {
            chrono.setBase(SystemClock.elapsedRealtime());
            chrono.start();
            mIsStarted = true;
        }

and then I stop it by:

        switch (item.getItemId()) {
            case R.id.item1:
                Toast.makeText(getApplicationContext(),"Count Reset",Toast.LENGTH_LONG).show();
                txtCount.setText(String.valueOf(count = 0));
                chrono.setBase(SystemClock.elapsedRealtime());
            return true;
            default:
                return super.onOptionsItemSelected(item);

I have tried everything I understand, but can not restart the chronometer on the button click after i press the reset menu button, instead it stays at 00. I understand that this is most likely because of

if (!mIsStarted) {
  ...
        mIsStarted = true;

which allows the button to only interact with the chronometer once. Is there a way to allow the button to start the chronometer after it has been reset? Thanks


Solution

  • Because I set boolean mIsStarted= false; initially to only allow the first button click to start the chronometer after reset through menu button the boolean was still active and would not let me restart the chronometer in the same way:

     if (!mIsStarted) {
                chrono.setBase(SystemClock.elapsedRealtime());
                chrono.start();
                mIsStarted = true;}
    

    I added mIsStarted = false; to my menu button action and all works as intended:

                    txtCount.setText(String.valueOf(count = 0));
                chrono.setBase(SystemClock.elapsedRealtime());
                chrono.stop();
                mIsStarted = false;
    

    I start the chronometer by the button click then stop and reset to 00:00 by the menu button and restart the same process by the same button click.