Android在Thread和Runnable中更新TextView

use*_*339 33 multithreading android textview runnable

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

问题是,当我忽略tvTime.setText(...)(使其//tvTime.setText(...),在logcat中会打印以下数量的每一秒.但是,当我想设置这个数字为TextView(在另一个Thread中创建),程序崩溃.

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

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

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();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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();
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*way 49

UserInterface只能由UI线程更新.你需要一个Handler来发布到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();
}
Run Code Online (Sandbox Code Playgroud)


den*_*rew 29

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

runOnUiThread(new Runnable() {
    public void run() {
        // Update UI elements
    }
});
Run Code Online (Sandbox Code Playgroud)