Aktualizacja Android TextView w wątku i Runnable
Chcę stworzyć prosty zegar w systemie Android, który aktualizuje TextView co sekundę. To po prostu liczy sekundy jak w grze Saper.
Problem polega na tym, że ignorując tvTime.setText (...) (make //tvTime.setText (...), w LogCat będzie drukowana następująca liczba co sekundę. Ale kiedy chcę ustawić tę liczbę na TextView (utworzony w innym wątku), program ulega awarii.
Czy ktoś ma pomysł, jak łatwo to rozwiązać?
Oto kod (metoda jest wywoływana przy starcie):
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();
}
EDYTOWAĆ:
W końcu to dostałam. Oto rozwiązanie dla zainteresowanych.
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();
}