相关疑难解决方法(0)

Android在Thread和Runnable中更新TextView

我想在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 …
Run Code Online (Sandbox Code Playgroud)

multithreading android textview runnable

33
推荐指数
2
解决办法
6万
查看次数

标签 统计

android ×1

multithreading ×1

runnable ×1

textview ×1