Search code examples
javaandroidhandlerrunnablecountdowntimer

How to set Countdown time format


I was use runnable() to make countdown timer on my game

i was set int cd=30;

and this is the method for run it

final Handler mHandler = new Handler();

final Runnable mUpdateTimeTasks = new Runnable() {

    public void run() {
        countdowntext.setText(String.valueOf(cd));
        cd -=1;
        if(cd < 10) {
            countdowntext.setTextColor(Color.RED);
        }
        if(cd == 0) {
           focus.stop();                                      
        }
    };
    // run this in a method.
    mHandler.postDelayed(mUpdateTimeTasks, cd);
}

the code was work fine but the problem just the coundown timer run so fast, i just wonder how to make int cd=1 = 1 second too, so cd=30 = 30 second

can anyone help me?


Solution

  • i just wonder how to make int cd=1 = 1 second too, so cd=30 = 30 second

    then you should use mHandler.postDelayed(mUpdateTimeTasks, 1000)

    final Runnable mUpdateTimeTasks = new Runnable() {
          public void run() {
               countdowntext.setText(String.valueOf(cd));
               cd -=1;
               if(cd < 10) {
                    countdowntext.setTextColor(Color.RED);
               }
               if(cd == 0) { 
                    focus.stop();        
                    mHandler.removaCallbacks(null);
                    return;                   
               }
               mHandler.postDelayed(this, 1000)
    };
    

    this will not give exactly 30 seconds but something really close to it