如何在Android中为TextView创建向上计数效果
问题内容:
我正在开发一个应用程序,该应用程序可以计算文本几段中问号的数量。
扫描完成后(根本不需要时间),我希望在数字从0变为TOTAL后再显示总数。因此,对于10:0,1,2,3,4,5,6,7,8,9 10 ,然后停止。
我尝试了几种不同的技术:
TextView sentScore = (TextView) findViewById(R.id.sentScore);
long freezeTime = SystemClock.uptimeMillis();
for (int i = 0; i < sent; i++) {
if ((SystemClock.uptimeMillis() - freezeTime) > 500) {
sentScore.setText(sent.toString());
}
}
我也试过这个:
for (int i = 0; i < sent; i++) {
// try {
Thread.sleep(500);
} catch (InterruptedException ie) {
sentScore.setText(i.toString());
}
}
我确信这些都是完全业余的尝试。任何帮助将非常感激。
谢谢,
理查德
问题答案:
试试这个:
private int counter = 0;
private int total = 30; // the total number
//...
//when you want to start the counting start the thread bellow.
new Thread(new Runnable() {
public void run() {
while (counter < total) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.post(new Runnable() {
public void run() {
t.setText("" + counter);
}
});
counter++;
}
}
}).start();