2010-06-29 4 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; 
    } 
}

, 나는 모든 두 번째는 두 번째 다른를 추가하는 타이머를하고 나는 표시 나는 makeView라는 알았는데 TextSwitcher의 텍스트를 설정해야 원하는 방식으로 포맷하지만 makeView 한 번만 호출되고 시간은 00:00:01으로 유지됩니다. 나는이 단계의 UI 객체가 잘 문서화되어 있다고 생각하지 않는다.

감사합니다. Jake

답변

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 
      } 
    } 
} 

그리고의 TimerTask의 run() 메소드에서

mHandler.sendMessage(msg); 

를 호출합니다.

이것은 현재 문제에 대한 해결책이지만 TimerTasks를 사용하지 않으면 더 좋은 방법이 될 수 있습니다.

+0

이전에는 핸들러를 사용하지 않았습니다. 그래서 그 switch 문에서 updateClock을 호출 할 수 있습니까? – jakehschwartz

+0

그리고 왜 makeView가 한 번 호출되었는지, 또 다시 호출되지는 않습니다. 나는이 솔루션이 충분히 복잡하다고 느낍니다. – jakehschwartz

+0

여기 실제로 당신이하려는 일의 예입니다. http://developer.android.com/resources/articles/timed-ui-updates.html –

관련 문제