JDS*_*JDS 47 java android timer
我正在使用计时器来制作秒表.计时器通过增加整数值来工作.我想通过不断更新textview在活动中显示此值.
这是我尝试更新活动的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);
}
Run Code Online (Sandbox Code Playgroud)
关于在错误的线程中更新UI,我遇到了一些错误.
如何调整我的代码来完成不断更新textview的任务?
Nir*_*rav 89
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
}
};
Run Code Online (Sandbox Code Playgroud)
上面的代码将工作...
注意:必须在主线程中创建处理程序,以便您可以修改UI内容.
StopWatch.time.post(new Runnable() {
StopWatch.time.setText(formatIntoHHMMSS(elapsedTime));
});
Run Code Online (Sandbox Code Playgroud)
此代码块基于Handler,但您不需要创建自己的Handler实例.
| 归档时间: |
|
| 查看次数: |
65491 次 |
| 最近记录: |