安卓 TextView 定时器

19
对于我的Android应用程序,有一个计时器来测量经过了多少时间。每100毫秒,我会更新我的TextView,显示一些文本,比如“得分:10 时间:100.10秒”。但是,我发现TextView只会在最开始的几次更新。应用程序仍然非常响应,但标签不会更新。我尝试调用.invalidate(),但它仍然无法工作。我不知道是否有一种方法来解决这个问题,或者使用更好的小部件。

这里是我的代码示例:

float seconds;
java.util.Timer gametimer;
void updatecount() { TextView t = (TextView)findViewById(R.id.topscore);
t.setText("Score: 10 - Time: "+seconds+" seconds");
t.postInvalidate();
}
public void onCreate(Bundle sis) {
... Load the UI, etc...
  gametimer.schedule(new TimerTask() { public void run() {
     seconds+=0.1; updatecount();
} }, 100, 100);
}
4个回答

19

谢谢您提供这个链接。那个页面上的代码完美地适用于我的基于TextView的计时器。 - RyanM

2
我认为发生的情况是您正在脱离UI线程。有一个单独的“looper”线程来处理所有屏幕更新。如果您尝试调用“invalidate()”,而您不在此线程上,则什么都不会发生。
尝试在您的视图上使用“postInvalidate()”。它将允许您在当前UI线程之外更新视图。
更多信息请参见此处

它仍然不起作用 - 它第一次更新,所以我知道它正在工作,但之后就不再更新了。无论如何,谢谢,艾萨克。 - Isaac Waller

1
使用以下代码在TextView上设置时间。
public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        @Override
        public void onFinish() {

            ExamActivity.this.submitresult();
        }

        @Override
        public void onTick(long millisUntilFinished) {

            long millis = millisUntilFinished;

            int seconds = (int) (millis / 1000) % 60;
            int minutes = (int) ((millis / (1000 * 60)) % 60);
            int hours = (int) ((millis / (1000 * 60`enter code here` * 60)) % 24);

            String ms = String
                    .format("%02d:%02d:%02d", hours, minutes, seconds);
            txtimedisplay.setText(ms);
        }
    }

0

还有一种每秒更改文本的方法; 这就是 ValueAnimator。这是我的解决方案:

  long startTime = System.currentTimeMillis();
  ValueAnimator animator = new ValueAnimator();
            animator.setObjectValues(0, 1000);
            animator.setDuration(1000);
            animator.setRepeatCount(ValueAnimator.INFINITE);
            animator.addListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationStart(Animator animation) {
                    long currentTime = System.currentTimeMillis();
                    String text = TimeFormatUtils.formatTime(startTime - currentTime);
                   yourTextView.setText(text);
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                    long currentTime = System.currentTimeMillis();
                    String text = TimeFormatUtils.formatTime(startTime - currentTime);
                    yourTextView.setText(text);
                }
            });
            animator.start();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接