TextSwitcher没有更新

时间:2010-06-29 18:22:44

标签: android

所以我有一个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;
    }
}

所以基本上,我有一个Timer,每秒都会增加另一秒,它们按照我想要显示的方式格式化并设置TextSwitcher的文本,我认为它叫做makeView,但是makeView只被调用一次而且时间停留00:00:01我是否错过了一个步骤,我不认为这个UI对象有很好的记录。

谢谢,杰克

1 个答案:

答案 0 :(得分: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,可能有更好的方法。