2010-06-29 70 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