Atualização do Android TextView em Thread e Runnable
Eu quero fazer um temporizador simples no Android que atualiza um TextView a cada segundo. Ele simplesmente conta segundos como no Campo Minado.
O problema é quando eu ignorar o tvTime.setText (...) (torná-lo //tvTime.setText (...), no LogCat será impresso o seguinte número a cada segundo. Mas quando eu quero definir este número para um TextView (criado em outro Thread), o programa trava.
Alguém tem uma ideia de como resolver isso facilmente?
Aqui está o código (o método é chamado na inicialização):
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();
}
EDITAR:
Finalmente, eu entendi. Aqui está a solução, para aqueles que estão interessados em.
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();
}