0

对于特定线程,我有以下代码

public void run() {

    while (true) {
        currentWord = words.get(new Random().nextInt(words.size()));
        tvForeignWord.setText(currentWord.getWordForeign());
        tvScore.setText("Your score is " + score);
        for (int i = timer_length; i > 0; i--) {
            tvTimer.setText("You have " + i + " seconds remaining.");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //DEBUG e.printStackTrace();
            }
        }
    }
}

但是,我似乎收到此错误消息:

02-19 22:03:38.950: E/AndroidRuntime(17236): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

问题是什么?

当我这样做时:

public void run() {

    //while (true) {
        currentWord = words.get(new Random().nextInt(words.size()));
        tvForeignWord.setText(currentWord.getWordForeign());
        tvScore.setText("Your score is " + score);
        //for (int i = timer_length; i > 0; i--) {
            //tvTimer.setText("You have " + i + " seconds remaining.");
            //try {
                //Thread.sleep(1000);
            //} catch (InterruptedException e) {
                //DEBUG e.printStackTrace();
            //}
        //}
    }

我没有错误?

4

2 回答 2

1

您不应该从单独的线程更新 UI。要么在你的线程之外创建一个 Handler 对象并将可运行对象发布到该对象,要么尝试使用 context.runOnUiThread() 在主线程上执行你的 UI 操作。

于 2013-02-19T22:20:48.340 回答
0

只允许 UI 线程操作 UI 对象。您需要在 UI 线程和工作线程之间设置消息传递,以便工作线程在屏幕上产生更改。

于 2013-02-19T22:08:31.677 回答