2016-04-24 82 views
0

我想用不同的字符串每3秒更新一次TextView。我有一個處理程序和runnable設置,但是當我運行它時,它會自動顯示最後一個setText。我試圖將ms更改爲3000,6000等,並且在運行之前也嘗試了removeCallbacks。任何幫助將不勝感激!用Handler更新TextVIew只顯示最後一次更改

final Handler handler = new Handler(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.workout); 

    final Runnable r = new Runnable(){ 
     @Override 
     public void run(){ 
      TextView text = (TextView)findViewById(R.id.textView4); 
      text.setText("1"); 
      handler.postDelayed(this, 3000); 
      text.setText("2"); 
      handler.postDelayed(this, 3000); 
      text.setText("3"); 
      handler.postDelayed(this, 3000); 
      text.setText("4"); 
      handler.postDelayed(this, 3000); 
      text.setText("5"); 


     } 
    }; 

    handler.postDelayed(r, 0); 


} 

回答

0

更改您這樣的代碼

private String[] messages = {"1", "2", "3", "4", "5"}; 
    final Handler handler = new Handler(); 
    private int nextIndex; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.workout); 
     final TextView text = (TextView)findViewById(R.id.textView4); 
     final Runnable r = new Runnable(){ 
      @Override 
      public void run(){ 
       if (messages.length > nextIndex) { 
        text.setText(messages[nextIndex++]); 
        handler.postDelayed(this, 3000); 
       } 
      } 
     }; 

     handler.postDelayed(r, 0); 
    } 
+0

你是一個天才,太感謝你了!完美的作品! – SillyFidget