Android的定时更新一个TextView(UI)Android、TextView、UI

由网友(孤人自嘲)分享简介:我用一个定时器来创建一个秒表。定时器的工作原理,通过增加一个整数值。我想然后通过不断更新一个TextView显示在活动这个值。 下面是我从那里我尝试更新活动的TextView的服务code:受保护的静态无效startTimer(){isTimerRunning = TRUE;timer.scheduleAtFixedR...

我用一个定时器来创建一个秒表。定时器的工作原理,通过增加一个整数值。我想然后通过不断更新一个TextView显示在活动这个值。

下面是我从那里我尝试更新活动的TextView的服务code:

 受保护的静态无效startTimer(){
    isTimerRunning = TRUE;
    timer.scheduleAtFixedRate(新的TimerTask(){
        公共无效的run(){
            elapsedTime + = 1; //每增加秒
            StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //这是TextView的
        }
    },0,1000);
}
 

我得到了某种错误有关更新的用户界面,在错误的线程。

我如何能适应我的code来实现不断更新的TextView这个任务吗?

感谢。

解决方案

 受保护的静态无效startTimer(){
    isTimerRunning = TRUE;
    timer.scheduleAtFixedRate(新的TimerTask(){
        公共无效的run(){
            elapsedTime + = 1; //每增加秒
            mHandler.obtainMessage(1).sendToTarget();

        }
    },0,1000);
};

公开处理程序mHandler =新的处理程序(){
    公共无效的handleMessage(信息MSG){
        StopWatch.time.setText(formatIntoHHMMSS(elapsedTime)); //这是TextView的
    }
}
 
AndroidUI之TextView属性讲解

以上code必须工作......

注:mHandler必须在主线程中创建

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

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?

Thanks.

解决方案

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 must work...

Note:mHandler must be created in your main thread.

阅读全文

相关推荐

最新文章