简体   繁体   中英

How do I display countdown timer in TextView?

I have Calendar Object

Calendar cal = Calendar.getInstance();
int hh = cal.get(Calendar.HOUR);
int mm = cal.get(Calendar.MINUTE);
int ss = cal.get(Calendar.SECOND);

And to format time

SimpleDateFormat sdf = new SimpleDateFormat("h:mm:s a", Locale.US);

I want my TextView to display count down time in hh:mm:ss format

Time left: 03:25:12
Time left: 03:25:11
Time left: 03:25:10 
Time left: 03:25:09
.
.
. so on and stop the countdown after 3 hours, 25 minutes and 8 seconds.

After times is lapsed the TextView should display Time left: 00:00:00 .

use the Timer class as:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

long maxTimeInMilliseconds = 3*25*8*1000;// in your case

startTimer(maxTimeInMilliseconds, 1000);

}

public void startTimer(final long finish, long tick)
    {
        t = new CountDownTimer(finish, tick) {

        public void onTick(long millisUntilFinished) 
        {           
            long remainedSecs = millisUntilFinished/1000;
            timer.setText(""+(remainedSecs/60)+":"+(remainedSecs%60));// manage it accordign to you
        }

        public void onFinish() 
        {
             timer.setText("00:00:00");
             cancel();
        }
        }.start();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM