我无法从线程更改TextView文本

时间:2015-01-11 15:46:43

标签: android multithreading settext

我试图从我的线程中更改textView,但它总是崩溃。为什么呢?

public void startProgress(View view) {

    bar.setProgress(0);
    new Thread(new Task()).start();
}

class Task implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i <= 10; i++) {
            final int value = i;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            bar.setProgress(value);
            text.setText("i = "+i);
        }
    }
}

我不知道为什么我无法改变它。谁知道为什么?

感谢。

4 个答案:

答案 0 :(得分:0)

视图只能由其父线程修改。这是人们面临的一个常见问题,不幸的是,你只需要解决它。

答案 1 :(得分:0)

使用runOnUiThread

runOnUiThread(new Runnable(){
    public void run() {
        for (int i = 0; i <= 10; i++) {
           final int value = i;
           try {
              Thread.sleep(1000);
           } catch (InterruptedException e) {
            e.printStackTrace();
          }
          bar.setProgress(value);
          text.setText("i = "+i);
       }
    }
});

答案 2 :(得分:0)

正如@dodo或@CommonsWare所说,你必须在主ui线程中访问View hiearhcy。 要遵守此规则,请使用 Handler.post(Context.getMainLooper())

new Handler(context.getMainLooper()).post(new Runnable() {
    public void run() {
        bar.setProgress(value);
        text.setText("i = "+i);
    }
});

答案 3 :(得分:0)

最后我修好了。不管怎样,谢谢。

public void startProgress(View view) {

    bar.setProgress(0);
    //new Thread(new Task()).start();

    Thread th = new Thread(new Runnable() {
        public void run() {
            for (int i=0; i<10;i++){           
                final int timer = i;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        text.setText("velocitat: "+timer);
                    }
                });
                bar.setProgress(timer);
                try {
                    Thread.sleep(1000);
                } 
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    th.start();
}