Countdown timer with pause and resume

后端 未结 8 906
小蘑菇
小蘑菇 2021-01-05 04:17

I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdow

8条回答
  •  花落未央
    2021-01-05 04:43

    public class MainActivity extends AppCompatActivity {
    
    TextView textView;
    
    CountDownTimer ctimer;
    boolean runCountDown;
    private long leftTime;
    private static final long MILL_IN_FUTURE = 6000;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        textView = findViewById(R.id.text_view);
        textView.setText("Click to start");
        textView.setOnClickListener(this::clickStartAndPauseAndResume);
        leftTime = MILL_IN_FUTURE;
    
    }
    
    
    public void clickStartAndPauseAndResume(View view) {
    
        if (!runCountDown) {
    
    
            long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
            ctimer = new CountDownTimer(time, 1) {
    
                @Override
                public void onTick(long l) {
    
                    leftTime = l;
                    textView.setText(l + "ms");
                }
    
                @Override
                public void onFinish() {
    
                    textView.setText("Done");
                    leftTime = 0;
                    runCountDown = false;
                    textView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("Click to start");
                        }
                    }, 1000);
                }
            }.start();
            runCountDown = true;
        } else {
            ctimer.cancel();
            textView.setText(textView.getText() + "\n Click to resume");
            runCountDown = false;
        }
     }
    }
    

提交回复
热议问题