0

我正在为 android 制作秒表应用程序。我有一个启动和停止按钮。我的问题是时间增长得非常快。我哪里错了。下面是代码:

        final Runnable updater = new Runnable() {

        public void run() {

            if (startIsPressed) {
                time = SystemClock.elapsedRealtime() - initStart + startPointTime;
                startPointTime = time;
            } else {
                time = startPointTime;
            }

            hh = time / 3600000;
            hours.setText("" + formatter.format(hh));
            time = time - hh * 3600000;

            mm = time / 60000;
            minutes.setText("" + formatter.format(mm));
            time = time - mm * 60000;

            ss = time / 1000;
            seconds.setText("" + formatter.format(ss));
            time = time - ss * 1000;

            millis.setText("" + formatter.format(time / 10));

            handler.postDelayed(this, 30);
        }
    };
    startBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (!startIsPressed) {
                startIsPressed = true;
                startBtn.setText(R.string.stop);
                initStart = SystemClock.elapsedRealtime();
                handler.post(updater);
            } else {
                startIsPressed = false;
                startBtn.setText(R.string.start);
                handler.post(updater);
            }
        }
    });
}
4

1 回答 1

1

正如文档所说postDelayed导致 Runnable r 添加到消息队列中,在指定的时间过去后运行。每 1 秒更新一次计时器:使用

handler.postDelayed(this, 100); //100 milliseconds refresh rate

代替

handler.postDelayed(this, 30); //30 milliseconds refresh rate

并在此处查看秒表逻辑

于 2012-05-12T12:33:30.517 回答