【问题标题】:Display charecters in textview with time delay - android在文本视图中显示具有时间延迟的字符 - android
【发布时间】:2011-10-01 03:53:08
【问题描述】:

我想使用 textview 显示字母。并且 字母应该在一段时间后显示在 textview 中

我使用了以下代码....

String a="Apple";
String b="";
.......
.......


public void run() {

    for (int i = 0; i < 5; i++) {
        b=b+""+a.charAt(i);
        mTextView.setText(b); //Problem here
        Log.d("Letters",""+b);
            try {
                  sleep(2000); 
           } catch (InterruptedException e) {}
    }

记录猫结果: android.view.ViewRoot$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。
任何解决方案?

【问题讨论】:

    标签: java android multithreading time


    【解决方案1】:

    您不能从其他线程更改 UI 控件。以另一种方式更新您的代码:

    public void run() {
    
        for (int i = 0; i < 5; i++) {
            b=b+""+a.charAt(i);
    
            //one of the ways to update UI controls from non-UI thread.
            runOnUiThread(new Runnable()
            {               
                @Override
                public void run()
                {
                    mTextView.setText(b); //no problems here :)                 
                }
            });
    
            Log.d("Letters",""+b);
                try {
                      sleep(2000); 
               } catch (InterruptedException e) {}
        }
    }
    

    【讨论】:

      【解决方案2】:

      您无法在线程中更新文本视图,因为 UI 更新不是线程安全的。

      使用这个

          public void run() {
      
              for (int i = 0; i < 5; i++) {
                  b=b+""+a.charAt(i);
      
                  Log.d("Letters",""+b);
                      try {
                            sleep(2000); 
                            handler.post(updateMessgae)
                     } catch (InterruptedException e) {}
              }
      
      private final Runnable updateMessgae= new Runnable() 
          {
              public void run() 
              {
                  try 
                  {
                  Log.d("Letters",""+b);  
                  } 
                  catch (Exception e) 
                  {
                      e.printStackTrace();
                  }
              }
          };
          private final Handler handler = new Handler();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-19
        • 1970-01-01
        • 2019-10-26
        • 1970-01-01
        • 2020-10-02
        • 1970-01-01
        相关资源
        最近更新 更多