2010-06-29 19 views
0

所以我有一個TextSwitcher,我想每秒鐘更新它自打開活動以來的秒數。這裏是我的代碼TextSwitcher沒有更新

public class SecondActivity extends Activity implements ViewFactory 
{ 
    private TextSwitcher counter; 
    private Timer secondCounter; 
    int elapsedTime = 0; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     // Create the layout 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.event); 

     // Timer that keeps track of elapsed time 
     counter = (TextSwitcher) findViewById(R.id.timeswitcher); 
     Animation in = AnimationUtils.loadAnimation(this, 
       android.R.anim.fade_in); 
     Animation out = AnimationUtils.loadAnimation(this, 
       android.R.anim.fade_out); 
     counter.setFactory(this); 
     counter.setInAnimation(in); 
     counter.setOutAnimation(out); 

     secondCounter = new Timer(); 
     secondCounter.schedule(new TimerUpdate(), 0, 1000); 
    } 

    /** 
    * Updates the clock timer every second 
    */ 
    public void updateClock() 
    {   
     //Update time 
     elapsedTime++; 
     int hours = elapsedTime/360; 
     int minutes = elapsedTime/60; 
     int seconds = elapsedTime%60; 

     // Format the string based on the number of hours, minutes and seconds 
     String time = ""; 

     if (!hours >= 10) 
     { 
      time += "0"; 
     } 
     time += hours + ":"; 

     if (!minutes >= 10) 
     { 
      time += "0"; 
     } 
     time += minutes + ":"; 

     if (!seconds >= 10) 
     { 
      time += "0"; 
     } 
     time += seconds; 

     // Set the text to the textview 
     counter.setText(time); 
    } 

    private class TimerUpdate extends TimerTask 
    { 
     @Override 
     public void run() 
     { 
      updateClock(); 
     } 
    } 

    @Override 
    public View makeView() 
    { 
     Log.d("MakeView"); 
     TextView t = new TextView(this); 
     t.setTextSize(40); 
     return t; 
    } 
}

所以基本上,我有一個計時器,每一秒鐘又增加了第二個和其格式化我要顯示和設置TextSwitcher,我認爲叫makeView的文本的方式,但makeView只會被調用一次,時間保持爲00:00:01。我錯過了一個步驟,我不認爲這個UI對象有很好的文檔記錄。

謝謝你,傑克

回答

1

只能更新UI線程的UI。所以在你的例子中你可以做這樣的事情。

private Handler mHandler = new Handler() { 
    void handleMessage(Message msg) { 
      switch(msg.what) { 
       CASE UPDATE_TIME: 
        // set text to whatever, value can be put in the Message 
      } 
    } 
} 

並調用

mHandler.sendMessage(msg); 
在TimerTask的的run()方法

這是對當前問題的解決方案,但可能有更好的方法來使用它,而不使用TimerTasks。

+0

我以前從未使用處理程序。所以我可以在該switch語句中調用updateClock? – jakehschwartz 2010-06-29 18:34:28

+0

我不明白爲什麼makeView被調用一次,然後不再。我覺得這個解決方案非常複雜。 – jakehschwartz 2010-06-29 18:36:33

+0

這裏實際上是你想要做的一個例子。 http://developer.android.com/resources/articles/timed-ui-updates.html – 2010-06-29 18:56:57