2012-09-05 26 views
1

我希望讓我的runnable不需要使用我的UI,而不是每75秒一次,我不想使用AnsyTask。但是TextView只是設置在for循環的結尾處,爲什麼?runnable中的SetText視圖無法正常工作

... 

robotWords = "........Hey hello user!!!"; 
     wordSize = robotWords.length(); 
     mHandler.postDelayed(r, 750); 
    } 

    private Runnable r = new Runnable() 
    { 
     public void run() 
     { 
      for(int i=0; i<wordSize; i++) 
      {   
       robotTextView.setText("why this words only display on the textView at last operation on this for loop?"); 
       Log.i(TAG, robotWords.substring(0, i)); 
       try 
       { 
        Thread.sleep(750); 
       } catch (InterruptedException e) 
       { 
        e.printStackTrace(); 
       } 
      } 

     } 
    }; 

回答

1

TextView的只設在for循環的結束,因爲這條線Thread.sleep(750);

你的線程將睡覺前文真的設爲您的TextView的。我想你應該叫Handler.postDelayed每750毫秒,而不是使用Thread.sleep(750);或使用CountDownTimer

new CountDownTimer(750 * wordSize, 750) { 

public void onTick(long millisUntilFinished) { 
    robotTextView.setText("why this words only display on the textView at last operation on this for loop?"); 
      Log.i(TAG, robotWords.substring(0, i)); 
} 

public void onFinish() {   
} 

}。開始();

1

你不應該從另一個線程調用UI線程。 使用CountDownTimer

new CountDownTimer(wordSize*750, 750) { 

     public void onTick(long millisUntilFinished) { 
      robotTextView.setText("..."); 
     } 

     public void onFinish() { 

     } 
    }.start(); 
+0

意識到我有第一個參數錯誤的CountDownTimer,認爲這是一個ScheduledRepeatingTask xD – StrikeForceZero

1

試試這個,叫 「doStuff()」 當你想要的操作發生

public void doStuff() { 
    new Thread(new Runnable() { 
     public void run() { 

    for(int i=0; i<wordSize; i++) {   
     robotTextView.setText("why this words only display on the textView at last operation on this for loop?"); 
     Log.i(TAG, robotWords.substring(0, i)); 


       robotTextView.post(new Runnable() { 
        public void run() { 
          robotTextView.setText("why this words only display on the textView at last operation on this for loop?"); 
        } 
       }); 

     try { 
      Thread.sleep(750); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

      } 
     } 
    }).start(); 
} 

希望這有助於!