close

在Android 如果要定時更新元件上的字,例如設計button上的倒數計時功能時,利用timer去更新,會得到下列錯誤訊息:

(user timer update button text, will get this error message:)

"Only the original thread that created a view hierarchy can touch its views."

 

使用timer 範例如下:

(this is my user timer example):

 

private Timer adTimeStartControl;
Button bADControl = (Button)findViewById(R.id._adControlButton);
long triggerSec = 3000;
adTimeStartControl.schedule(new startADCounter(), triggerSec, triggerSec);
class startADCounter extends TimerTask {
    @Override
    public void run() {
        if (timeCounter < 30) {
            if (DEBUG) Log.i(TAG, "startADTimeControl()::time Counter: " + timeCounter);
            String adString = "廣告即將啟動,:" + timeCounter;
            if (bADControl == null) {
                if (DEBUG) Log.i(TAG, "startADTimeControl()::bADControl == null");
                return;
            }
            bADControl.setText(adString);
        }
    }
}

 

當觸發更新setText就會引發下列錯誤:

(When timer trigger, will crash and get this error message:)

"Only the original thread that created a view hierarchy can touch its views."

 

錯誤也很明確指出必需在original thread下才能更新views.

(the message is told you the update views need on the original thread.)

 

所以我們改採用Runnable及postDelayed達到上述的功能要求,解決這問題:

(So, we user Runable and postDelayed function to get outs purpose.)

 

private Handler AdHandler;
private Runnable AdHandTask;

Button bADControl = (Button)findViewById(R.id._adControlButton);

AdHandler = new Handler();
AdHandTask = new Runnable() {
    @Override
    public void run() {
        String adString = "廣告即將啟動:" + timeCounter ;
        bADControl.setText(adString);
        timeCounter++;
        AdHandler.postDelayed(AdHandTask, 1000);
    }
};
AdHandTask.run();

相同達到時間控制元件的更新功能,且沒有錯誤。

(so, this method can update button and timer terget.)

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 竹科工程師 的頭像
    竹科工程師

    竹科工程師( software engineer ) DIY Car Cefiro A32 的部落格(第二區)

    竹科工程師 發表在 痞客邦 留言(0) 人氣()