对于我的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);
}
发布于 2009-11-27 00:58:28
一般的解决方案是使用在UI线程中运行的android.os.Handler。它只做一次回调,所以每次调用你的回调时,你都必须再次触发它。但是它很容易使用。几年前写过一篇关于这个话题的博客文章:
http://android-developers.blogspot.com/2007/11/stitch-in-time.html
发布于 2009-02-07 03:30:23
我认为正在发生的事情是你正在脱离UI线程。只有一个"looper“线程来处理所有的屏幕更新。如果你试图调用"invalidate()“,而你不在这个线程上,那么什么都不会发生。
尝试在视图上使用"postInvalidate()“。它可以让你在不在当前UI线程中的时候更新视图。
更多信息here
发布于 2014-12-19 22:00:02
使用以下代码在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);
}
}
https://stackoverflow.com/questions/522800
复制相似问题