Android update TextView in Thread and Runnable

孤街醉人 提交于 2019-11-26 22:08:11

The UserInterface can only be updated by the UI Thread. You need a Handler, to post to the UI Thread:

private void startTimerThread() {
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {  
                try {
                    Thread.sleep(1000);
                }    
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable(){
                    public void run() {
                       tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000));
                }
            });
            }
        }
    };
    new Thread(runnable).start();
}
dennisdrew

Alternatively, you can also just do this in your thread whenever you want to update a UI element:

runOnUiThread(new Runnable() {
    public void run() {
        // Update UI elements
    }
});

You cannot access UI elements from non-UI threads. Try surrounding the call to setText(...) with another Runnable and then look into the View.post(Runnable) method.

As an option use runOnUiThread() to change de views properties in the main thread.

  runOnUiThread(new Runnable() {
        @Override
        public void run() {       
                textView.setText("Stackoverflow is cool!");
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!