Android的TextView的计时器计时器、Android、TextView

2023-09-06 01:44:53 作者:零负荷的放任

有关我的Andr​​oid应用程序存在测量多少时间已经过去了一个计时器。自从100毫秒更新我的TextView中包含一些文本得分:10时间:100.10秒。但是,我发现的TextView只更新第几次。该应用还非常敏感,但标签不会更新。席力图召.invalidate(),但它仍然无法正常工作。我不知道是否有某种方式来解决这个问题,或者更好的插件使用。

下面是我的code一个例子:

 浮动秒;
java.util.Timer中gametimer;
无效使用UpdateCount(){TextView的T =(TextView中)findViewById(R.id.topscore);
t.se​​tText(得分:10  - 时间:+秒+秒);
t.postInvalidate();
}
公共无效的onCreate(包虫病){
...加载的UI等...
  gametimer.schedule(新的TimerTask(){公共无效的run(){
     秒+ = 0.1;使用UpdateCount();
}},100,100);
}
 
android计时器最简单,Android简单计时器

解决方案

一般的解决方法是使用android.os.Handler,而不是它运行在UI线程。它只做一锤子回调,所以你必须每次回调被调用时再次触发。但它是很容易使用。关于这个主题的博客帖子写了几年前:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html

For my Android application there is a timer that measures how much time has passed. Ever 100 milliseconds I update my TextView with some text like "Score: 10 Time: 100.10 seconds". But, I find the TextView only updates the first few times. The application is still very responsive, but the label will not update. I tried to call .invalidate(), but it still does not work. I don't know if there is some way to fix this, or a better widget to use.

Here is a example of my code:

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);
}

解决方案

The general solution is to use android.os.Handler instead which runs in the UI thread. It only does one-shot callbacks, so you have to trigger it again every time your callback is called. But it is easy enough to use. A blog post on this topic was written a couple of years ago:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html