我想在Android中制作一个简单的计时器,每秒更新一次TextView.它只是像扫雷一样计算秒数.
问题是,当我忽略tvTime.setText(...)(使其//tvTime.setText(...),在logcat中会打印以下数量的每一秒.但是,当我想设置这个数字为TextView(在另一个Thread中创建),程序崩溃.
有谁知道如何轻松解决这个问题?
这是代码(启动时调用方法):
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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:
终于我明白了.对于那些感兴趣的人来说,这是解决方案.
private void startTimerThread() {
Thread th = new Thread(new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
while (gameState …Run Code Online (Sandbox Code Playgroud)