格式倒数计时器在少于十秒的时间内使用前导零位数

时间:2013-11-15 08:15:59

标签: android

我的倒数计时器需要以正确的格式显示秒数。它目前都是正确的,直到计数不到10秒。

此时显示如下:9 8 7 6 5 4 3 2 1。我需要格式为09 08 06 05 04 03 02 01

以下是计时器代码:

private CountDownTimer timer(int time)
{
    CountDownTimer a = new CountDownTimer(time, 1000) 
    {
        public void onTick(long millisUntilFinished) {
            String clock;
            clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":" + ((millisUntilFinished / 1000)%60);
            Clk.setText(clock);
            // mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        }

        public void onFinish() {
            alarm.start();
            Clk.setText("00:00");
        }
    }.start();

    return a;
}

5 个答案:

答案 0 :(得分:1)

检查您收到的秒数是否小于10,如果这样,在setText之前将{0}添加到其前面

if((millisUntilFinished / 1000) % 60 < 10)
    clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":0" + ((millisUntilFinished / 1000)%60);
else
    clock = "" + ((millisUntilFinished / 1000)/60)%60 + ":" + ((millisUntilFinished / 1000)%60);

答案 1 :(得分:1)

尝试使用String.format

int remaining = ((millisUntilFinished / 1000)%60);
clock = String.format("seconds remaining: %02d .", remaining);

答案 2 :(得分:1)

clock = "" + (String.format("%02d",(millisUntilFinished / 1000)/60)%60) + ":" + (String.format("%02d",((millisUntilFinished / 1000)%60));

            Clk.setText(clock);

使用

String.format("%02d",9) //provides 09

答案 3 :(得分:1)

int seconds = millisUntilFinished / 1000;
Clk.setClock(String.format("%02d:%02d", seconds / 60, seconds % 60));

这将显示:

12:34
07:45
00:10
00:09
00:00

答案 4 :(得分:1)

int minutes = 15;
int seconds = 1;
String display = String.format("%02d:%02d", minutes, secconds);
System.out.println("display= " + display)