2013-10-27 19 views
0

你能告訴我這一行的問題在哪裏:timerText.setText(seconds);適用於Android的Java定時器

public class ShowTimer extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.timer_test_xml); 

     Timer myTimer = new Timer(); 
     myTimer.schedule(new TimerTask() { 
      int seconds; 
      TextView timerText = (TextView) findViewById(R.id.TimerTestId); 
      @Override 
      public void run() { 
       seconds++; 
       timerText.setText(seconds); 
      } 
     }, 0, 1000); 

    }} 
+0

的'的setText(INT)'Android上的功能有沒有文件,所以我真的不知道它做什麼。你確定它想要調用的功能嗎? –

+0

如果我們把一個字符串作爲方法的參數仍然不起作用:) – user2837445

+0

你想要發生什麼以及實際發生了什麼? –

回答

0

我想你想要做的是在文本視圖中顯示seconds。然而,TextView.setText(int)函數不會這樣做(我實際上不確定它做了什麼)。你想要做的是timerText.setText(""+seconds);將參數轉換爲一個字符串,並將函數調用更改爲不同的重載函數。

0

seconds是一個int,而我認爲你想要作爲字符序列傳遞,或通過資源ID as per the documentation傳遞給一個人。

0

雖然這並不回答OP的原題,也有替代性(和 - 如果你從Android文檔的建議達成一致意見 - 更好)的方法來做到這一點this thread描述。

0

與Richard的建議一樣,您的其他問題是更新非UI線程上的TextView,因此請考慮使用Handler

public class ShowTimer extends Activity { 

    private Handler mHandler; 
    private TextView timerText = null; 
    private int seconds; 

    private Runnable timerRunnable = new Runnable() { 
     @Override 
     public void run() { 
      timerText.setText(String.valueOf(seconds++)); 
      mHandler.postDelayed(timerRunnable, 1000); 
     } 
    }; 

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

     mHandler = new Handler(); 

     timerText = (TextView) findViewById(R.id.TimerTestId); 
     timerRunnable.run(); 
    } 
}