Android计时器更新文本视图(UI)

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内容.

  • @Nirav你可能想要告诉人们Handler的包是android.os而不是其他的. (7认同)

ina*_*ruk 8

您应该Handler每隔X秒使用更新UI.这是另一个显示示例的问题:重复一个延迟时间的任务?

您的方法不起作用,因为您尝试从非UI线程更新UI.这是不允许的.


Don*_*gXu 6

StopWatch.time.post(new Runnable() {
    StopWatch.time.setText(formatIntoHHMMSS(elapsedTime));
});
Run Code Online (Sandbox Code Playgroud)

此代码块基于Handler,但您不需要创建自己的Handler实例.

  • 未来读者请注意:Android中没有内置的"StopWatch"类; 这个答案是指OP的代码示例,其中"StopWatch"是OP的TextView的名称. (31认同)