Android Studio 中的计时器使用 Runnable



我正在尝试做一个计时器,但它只是不起作用,我不知道我应该改变什么才能让它工作。伙计们,你能帮我吗?

private TextView timer;
private boolean run = true;
private Integer a = 0;

. . .

public void Start(View view) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Integer count = a;
String sec = count.toString();
timer = findViewById(R.id.textView);
timer.setText(sec);
Thread.sleep(1000);
} catch (Exception e) {
timer.setText("Какая-то ошибка");
} if (run) {
a++;
}
}
}
);
t.start();
}

尝试使用Handler而不是Thread

public void Start(View view) {
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Integer count = a;
String sec = count.toString();
timer = findViewById(R.id.textView);
timer.setText(sec);
if (run) {
a++;
}
handler.postDelayed(this, 1000);
}
};

handler.postDelayed(runnable, 1000);
}

如果要实现倒计时并在文本视图中显示它。您可以简单地使用 android.os.CountDownTimer 类来代替