2013-11-22 104 views
0

我有一個表的一些值,我想每10秒更新UI(值)。我想向用戶展示一個倒數計時器,以知道將會發生什麼...... 但它崩潰。 我用的代碼如下所示:在Android的倒計時計時器

tv2_r7= (TextView) this.findViewById(R.id.textView2_r7); 

    final Timer timer = new Timer(); 
    timer.scheduleAtFixedRate(new TimerTask() { 
     int i = 10; 
     public void run() { 
      tv2_r7.setText(String.valueOf(i)); 
      i--; 
      if (i< 0) 
       timer.cancel(); 
     } 
    }, 0, 1000); 

它運作良好,在簡單的Java應用程序時,我的System.out.println(i--);代替tv2_r7.setText(String.valueOf(i)); i--;

+1

使用Android的計時器:http://developer.android.com/reference/android/os/CountDownTimer.html – zapl

回答

2

此時已更新計時器的UI值是錯誤的。你需要使用

runOnUIThread

方法那裏。

tv2_r7 = (TextView) this.findViewById(R.id.textView2_r7); 

    final Timer timer = new Timer(); 
    timer.scheduleAtFixedRate(new TimerTask() 
    { 
     int i = 10; 

     public void run() 
     { 
      runOnUIThread(new Runnable() 
      { 

       @Override 
       public void run() 
       { 
        tv2_r7.setText(String.valueOf(i)); 

       } 
      }); 

      i--; 
      if (i < 0) 
       timer.cancel(); 
     } 
    }, 0, 1000); 
} 
+0

謝謝。你的權利是我的問題 –