我正在尝试实现以下功能:按下按钮,每1秒在文本视图中显示从1到10的数字。
private void startCounting() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
increaseNumber();
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
}
private void increaseNumber() {
number++;
tvFragment.setText(number);
}
我遇到了 CalledFromWrongThreadException
错误。
好的,我知道这是什么,我们不能从后台线程更新 UI 元素,但问题是如何修复它?怎么做呢?
handler.removeCallbacksAndMessages(null);
should work. From https://developer.android.com/reference/android/os/Handler#removeCallbacks(java.lang.Runnable). You could also just stop it when it hits some number in the code, withif( number < maxNum ) handler.postDelayed(this, 1000)
- Tyler V