I have developed a Count Down Timer and I am not sure how to pause and resume the timer as the textview for the timer is being clicked. Click to start then click again to pa
I have a simple solution. All you have to do is add an extra variable which stores the current time. The only addition is currentMillis at top and in onTick(). Use cancel() to pause.
PS: I'm using butterknife library, it's used to avoid using findviewbyid and setonclicklisteners. If you do not want to use it then you can just use the basic way of setting listeners and findviewbyid.
@BindView(R.id.play_btn) ImageButton play;
@BindView(R.id.pause_btn) ImageButton pause;
@BindView(R.id.close_btn) ImageButton close;
@BindView(R.id.time) TextView time;
private CountDownTimer countDownTimer;
private long currentMillis=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
ButterKnife.bind(this);
}
@OnClick(R.id.play_btn) void play_game(){
this.play();
}
@OnClick(R.id.pause_btn) void pause_game(){
this.pause();
}
@OnClick(R.id.close_btn) void close_game(){
this.close();
}
void play(){
play.setVisibility(View.GONE);
close.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
time.setText(""+currentMillis);
countDownTimer = new CountDownTimer(currentMillis*1000,1000) {
@Override
public void onTick(long millisUntilFinish) {
currentMillis=millisUntilFinish/1000;
time.setText(""+millisUntilFinish/1000);
}
@Override
public void onFinish() {
time.setText("Done!");
}
};
countDownTimer.start();
}
void pause(){
play.setVisibility(View.VISIBLE);
close.setVisibility(View.VISIBLE);
pause.setVisibility(View.GONE);
countDownTimer.cancel();
}
void close(){
if(countDownTimer!=null){
countDownTimer.cancel();
countDownTimer=null;
}
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
}