Android update TextView in Thread and Runnable

后端 未结 4 493
栀梦
栀梦 2020-11-27 14:18

I want to make a simple timer in Android that updates a TextView every second. It simply counts seconds like in Minesweeper.

The problem is when i ignore the tvTime.

4条回答
  •  广开言路
    2020-11-27 14:21

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

提交回复
热议问题