Android计时器向后计数

时间:2017-03-04 14:39:38

标签: android countdown chronometer

我是Android开发的新手,目前正在尝试实现一个非常简单的倒数计时器,该计时器在到达00:00后继续计数,但在00:00以下时文本颜色为红色。

我有两个问题: 1)它从我设置的一秒开始计数(在示例中它从00:09而不是00:10开始)。 2)到达00:00后,在下一个刻度线上将文本变为红色,但将计数器保持在00:00(后一部分不是预期的),然后继续计数为-00:01,-00:02等所以它在00:00计数两次,一次是白色,一次是红色。有没有想过为什么会这样?这是我的代码:

public class myTimerActivity extends Activity {

    Chronometer mainTimer;
    long mStartValue = 10; // Countdown value

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

        // Set the user interface for this Activity
        setContentView(R.layout.activity_mytimer);

        // Initialize Chronometer object
        mainTimer = (Chronometer) findViewById(R.id.chronometer);
        mainTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                if (SystemClock.elapsedRealtime()>=chronometer.getBase()) {
                chronometer.setTextColor(Color.parseColor("#FF0000"));
                };
            }
        });
        mainTimer.setFormat("%s");
        mainTimer.setBase(SystemClock.elapsedRealtime()+mStartValue*1000);
        mainTimer.start();
    }
    ...
}

更新: 这是Roger建议的另一个实现:

public class myTimerActivity extends Activity {

    long mStartValue = 10; // Countdown value
    private TextView txtCounter;
    private static final String FORMAT_COUNTER = "%02d:%02d:%02d";

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

        // Set the user interface for this Activity
        setContentView(R.layout.activity_mytimer);
        txtCounter = (TextView)findViewById(R.id.mTextField);

        new CountDownTimer(mStartValue*1000, 1000) {

            public void onTick(long millisUntilFinished) {
                txtCounter.setText("" + String.format(FORMAT_COUNTER,
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished), // HOURS PASSED
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)), // MINUTES PASSED (over the hours)
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)) // SECONDS PASSED (over the minutes)
                ));
            }

            public void onFinish() {
                txtCounter.setTextColor(Color.parseColor("#FF0000"));
            }
        }.start();

    }
    ...
}

0 个答案:

没有答案