简体   繁体   中英

how to reset countdowntimer each time on starting it with new values?

I am making an app which uses CountDownTimer and shows each second value in a text view. I have 3 buttons with different times but on pressing the different buttons, the value on textview shows the CountDownTimer value of all the times simultaneously how to reset countdowntimer each time before calling it.

    package com.rebootapp.myapplication;

    import android.os.CountDownTimer;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {
    TextView textView;
    CountDownTimer countDownTimer;

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

        textView = findViewById(R.id.timer);

    }

    public void runtimer(View view) {
        switch (view.getId()) {
            case R.id.min3:
                countDownTimer.cancel();
                timer(10000);
                break;
            case R.id.min5:
                countDownTimer.cancel();
                timer(20000);
                break;
            case R.id.min10:
                countDownTimer.cancel();
                timer(30000);
                break;
            default:
                textView.setText("");
                break;
        }
    }

    public void timer(int t){
            countDownTimer = new CountDownTimer(t, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    textView.setText("" + millisUntilFinished / 1000);
                }

                @Override
                public void onFinish() {

                }
            }.start();
    }

 }

i used this and the issue got resolved inside the timer() function and removed countdowntimer.cancel(); from all cases and it got resolved

 if (countDownTimer != null) {
        countDownTimer.cancel();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM