我想在安卓系统中做一个简单的计时器,每秒钟更新一个TextView。它只是简单的计算秒,就像扫雷。
问题是当我忽略tvTime.setText(...)(make it //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();
}发布于 2012-10-04 05:21:00
UserInterface只能由UI线程更新。您需要一个Handler,才能发布到UI线程:
private void startTimerThread() {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
while (gameState == GameState.Playing) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
}
});
}
}
};
new Thread(runnable).start();
}发布于 2012-10-04 05:23:50
或者,当您想要更新UI元素时,也可以在线程中执行此操作:
runOnUiThread(new Runnable() {
public void run() {
// Update UI elements
}
});发布于 2017-03-30 07:12:21
可以选择使用runOnUiThread()来更改主线程中的de views属性。
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("Stackoverflow is cool!");
}
});https://stackoverflow.com/questions/12716850
复制相似问题