0

实际上,我设计了一个带有处理程序的单独 Timer 类,用于在 textview 上显示分钟和秒。这很好用,因为我已经对其进行了调试,并且处理程序将重新处理句柄,但文本视图没有得到更新,请在这方面帮助我。我将下面的代码标记为 Timer Class。提前致谢。

public class Timer
{
    private int _interval;
    public int getInterval()
    {
        return _interval;
    }
    public void setInterval(int delay)
    {
        _interval = delay;
    }
    private Handler handler;
    private Runnable _tickHandler;
    private Runnable delegate;
    private boolean ticking;
    public boolean getIsTicking()
    {
        return ticking;
    }
    public Timer(int interval)
    {
        _interval = interval;
        handler = new Handler();
    }
    public Timer(int interval, Runnable onTickHandler)
    {
        _interval = interval;
        setOnTickHandler(onTickHandler);
        handler = new Handler();
    }
    public void start(int interval, Runnable onTickHandler)
    {
        if (ticking) return;
        _interval = interval;
        setOnTickHandler(onTickHandler);
        handler.postDelayed(delegate, _interval);
        ticking = true;
    }
    public void start()
    {
        if (ticking) return;
        handler.postDelayed(delegate, _interval);
        ticking = true;
    }
    public void stop()
    {
        handler.removeCallbacks(delegate);
        ticking = false;
    }
    public void setOnTickHandler(Runnable onTickHandler)
    {
        if (onTickHandler == null)        return;
        _tickHandler = onTickHandler;
        delegate = new Runnable()
        {
            public void run()
            {
                if (_tickHandler == null) return;
                _tickHandler.run();
                handler.postDelayed(delegate, _interval);
            }
        }
        ;
    }
}

下面是我用于更新文本视图的代码

Timer tmr = new Timer(100,new Runnable()
{
    public void run()
    {
        long millis = System.currentTimeMillis() - mStartTime;
        int seconds = (int) (millis / 1000);
        int minutes = seconds / 60;
        seconds    = seconds % 60;
        lblDevOnOff.setText("");
        lblDevOnOff.setText(String.format("%d:%02d", minutes,seconds));
    }
}
);
tmr.start();
4

2 回答 2

1

将此代码放入

handlerrunOnUIThread()类似的东西

runOnUIThread(new Runnable(){

public void run(){

lblDevOnOff.setText("");
lblDevOnOff.setText(String.format("%d:%02d", minutes,seconds));
}
})

你应该这样做,因为与 UI 相关的任何东西都应该只在 UI 线程上运行......

于 2012-04-26T11:38:11.570 回答
0

是的,这是来自Android 开发指南

因此,Android 的单线程模型只有两条规则:

  • 不要阻塞 UI 线程
  • 不要从 UI 线程外部访问 Android UI 工具包
于 2012-04-26T11:45:12.770 回答