【发布时间】:2012-09-24 20:59:03
【问题描述】:
我想在 Android 中制作一个简单的计时器,每秒更新一个 TextView。它只是像扫雷一样计算秒数。
问题是当我忽略 tvTime.setText(...) 时(使其成为 //tvTime.setText(...),在 LogCat 中将每秒打印以下数字。 但是当我想将此数字设置为 TextView(在另一个线程中创建)时,程序崩溃了。
有人知道如何轻松解决这个问题吗?
代码如下(启动时调用方法):
private void startTimerThread() {
Thread th = new Thread(new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
while (gameState == GameState.Playing) {
System.out.println((System.currentTimeMillis() - this.startTime) / 1000);
tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
th.start();
}
编辑:
终于,我明白了。 以下是解决方案,有兴趣的朋友可以参考一下。
private void startTimerThread() {
Thread th = new Thread(new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
while (gameState == GameState.Playing) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000));
}
});
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
th.start();
}
【问题讨论】:
-
感谢 bud,这帮助很大!
-
但是当你点击返回按钮时它会崩溃
标签: android multithreading textview runnable