i wrote this code and i want when i click on btnGetPincode, a 60 sec count down timer start to run. but it didnt happen and the result in textview= 00:00 and nothing happen. why?
this is my code:
btnGetPinCode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnGetPinCode.setClickable(false);
btnGetPinCode.setBackgroundResource((R.drawable.button4));
txtShowPinCode.setVisibility(View.VISIBLE);
//initialize timer duration
long duration = TimeUnit.MINUTES.toMillis(1);
//initialize timer countdown timer
new CountDownTimer(duration, 1000) {
@Override
public void onTick(long millisUntilFinished) {
String duration2 = String.format(Locale.ENGLISH, "%02d : %02d"
, TimeUnit.MILLISECONDS.toMinutes(1)
, TimeUnit.MILLISECONDS.toSeconds(1) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(1)));
//set converted time to textView
txtTimer.setVisibility(View.VISIBLE);
txtTimer.setText(duration2+"");
btnOk.setText(duration2);
}
@Override
public void onFinish() {
//when timer finished, hide text view
txtTimer.setVisibility(View.INVISIBLE);
btnGetPinCode.setBackgroundResource(R.drawable.button);
btnGetPinCode.setClickable(true);
}
}.start();
});
}
Issue: You set 1
in each argument in duration2
variable, so the TextView won't ever be changed, you need to set the actual value that is changed on every timer tick which is the parameter of the onTick()
method >> millisUntilFinished
Change your timer to:
new CountDownTimer(duration, 1000) {
@Override
public void onTick(long millisUntilFinished) {
String duration2 = String.format(Locale.ENGLISH, "%02d : %02d"
, TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) //<<<<< change here
, TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - //<<<< change here
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))); //<<<<< change here
//set converted time to textView
txtTimer.setVisibility(View.VISIBLE);
txtTimer.setText(duration2+"");
btnOk.setText(duration2);
}
@Override
public void onFinish() {
//when timer finished, hide text view
txtTimer.setVisibility(View.INVISIBLE);
btnGetPinCode.setBackgroundResource(R.drawable.button);
btnGetPinCode.setClickable(true);
}
}.start();