Android 计时器更新文本视图(UI) [英] Android timer updating a textview (UI)
本文介绍了Android 计时器更新文本视图(UI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用计时器来创建秒表.定时器通过增加一个整数值来工作.然后我想通过不断更新文本视图在活动中显示这个值.
I'm using a timer to create a stop watch. The timer works by increasing a integer value. I want to then display this value in the activity by constantly updating a textview.
这是我尝试更新活动文本视图的服务中的代码:
Here's my code from the service where I try and update the activity's textview:
protected static void startTimer() {
isTimerRunning = true;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
elapsedTime += 1; //increase every sec
StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
}
}, 0, 1000);
}
我在错误的线程中更新 UI 时遇到某种错误.
I got some kind of error about updating the UI in the wrong thread.
如何调整我的代码以完成不断更新文本视图的任务?
How can I adapt my code to accomplish this task of constantly updating the textview?
推荐答案
protected static void startTimer() {
isTimerRunning = true;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
elapsedTime += 1; //increase every sec
mHandler.obtainMessage(1).sendToTarget();
}
}, 0, 1000);
}
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //this is the textview
}
};
以上代码会起作用...
Above code will work...
注意:必须在主线程中创建处理程序,以便您可以修改 UI 内容.
Note: Handlers must be created in your main thread so that you can modify UI content.
这篇关于Android 计时器更新文本视图(UI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文