【问题标题】:I can't change the TextView text from a thread我无法从线程更改 TextView 文本
【发布时间】:2015-01-11 15:46:43
【问题描述】:

我正在尝试从我的线程中更改一个 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);
        }
    }
}

我不知道为什么我不能改变它。有谁知道为什么?

谢谢。

【问题讨论】:

  • 您不能从后台线程修改 Activity 或 Fragment 的 UI,除非在少数选择情况下(例如,ProgressBar)。

标签: android multithreading settext


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 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);
           }
        }
    });
    

    【讨论】:

    • 当我使用 runOnUiThread 时它可以工作,但它只是在完成循环时更新内容。激活“startProgress”后,我无法触摸 UI 10 秒(持续循环的时间),然后显示文本更改为 i=10,但在此过程中 UI 被阻塞。
    【解决方案3】:

    正如@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);
        }
    });
    

    【讨论】:

      【解决方案4】:

      最后我修好了。还是谢谢。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-13
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 2014-02-07
        • 1970-01-01
        • 2019-04-01
        • 1970-01-01
        相关资源
        最近更新 更多