不明白为什么线程在Android中发生变化?

时间:2013-02-19 22:05:57

标签: android multithreading

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

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

我没有错误?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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