gpt4 book ai didi

java - Android Studio 中的计时器使用 Runnable

转载 作者:行者123 更新时间:2023-11-29 22:55:15 25 4
gpt4 key购买 nike

我正在尝试做一个计时器,但它根本不起作用,而且我无法弄清楚我应该更改什么才能使其起作用。你们能帮帮我吗?

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);
}

关于java - Android Studio 中的计时器使用 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com