如何在TextView中显示倒数计时器?

时间:2015-03-21 08:09:16

标签: android datetime timer textview countdown

我有Calendar对象

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

并格式化时间

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

我希望我的TextViewhh:mm:ss格式显示倒计时时间

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.

经过一段时间后,TextView应显示Time left: 00:00:00

1 个答案:

答案 0 :(得分:2)

将Timer类用作:

@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();
    }