Android update TextView in Thread and Runnable



我想在Android中制作一个简单的计时器,每秒更新一次TextView。它只是像扫雷一样计算秒数。

问题是当我忽略tvTime.setText(...)(让它//tvTime.setText(...))时,在LogCat中每秒将打印以下数字。但是当我想将此数字设置为文本视图(在另一个线程中创建)时,程序崩溃了。

有没有人知道如何轻松解决这个问题?

这是代码(启动时调用方法):

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

编辑:

终于,我明白了。对于那些感兴趣的人,这是解决方案。

private void startTimerThread() {       
    Thread th = new Thread(new Runnable() {
        private long startTime = System.currentTimeMillis();
        public void run() {
            while (gameState == GameState.Playing) {                
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000));
                    }
                });
                try {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}

用户界面只能由 UI 线程更新。您需要一个处理程序来发布到 UI 线程:

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

或者,您也可以在要更新 UI 元素时在线程中执行此操作:

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

作为一个选项,使用 runOnUiThread() 更改主线程中的 de views 属性。

  runOnUiThread(new Runnable() {
        @Override
        public void run() {       
                textView.setText("Stackoverflow is cool!");
        }
    });

不能从非 UI 线程访问 UI 元素。尝试用另一个Runnable将调用setText(...)包围起来,然后研究View.post(Runnable)方法。

最新更新