Display countdown in a toast from postDelayed method?

1.6k Views Asked by At

Using this method i can set a delay in an action i want do:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 5 seconds
  }
}, 5000);

Is there a way to display the countdown of this 5 seconds in a toast? Thanks

2

There are 2 best solutions below

1
On

If you mean that they stack up causing a delay then you should cancel the prior toast before showing a new one.

If you want something more fancy you could try using a PopupWindow instead to show the countdown, there you have more freedom for layout etc.

http://developer.android.com/reference/android/widget/PopupWindow.html

This is an answer by somebody else: https://stackoverflow.com/a/15174370/2767703


Example:

Toast toast = Toast.makeText(this, "10", Toast.LENGTH_SHORT);
toast.show();
new CountDownTimer(10000, 1000) {  
        public void onTick(long m) {  
           long sec = m/1000+1;  
           toast.cancel();
           toast.setText("" + sec);
           toast.show();
        }  
        public void onFinish() {  
           // Finished  
        }  
    }.start();
2
On

Yes Do following

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
      Log.i("seconds remaining: " ,""+ millisUntilFinished / 1000);
    }

    public void onFinish() {
         Log.i("Timer Finished");
    }  
}.start();