使用秒表值不断更新TextView

时间:2013-01-03 18:21:57

标签: java android

我正在尝试在我的Android活动中实现一个非常简单的秒表小部件,以便用户可以点击启动/重置以启动计时器,并停止停止它。所有的功能都在那里,但我似乎找不到一种方法来不断显示这个秒表的价值。

我目前正在使用一个自定义对象,该对象存储long值,表示创建Stopwatch对象的时间,构造函数将此long值设置为当前时间,以及一个displayTime方法,通过从原始时间减去当前时间并除以1000.0,返回表示当前时间的double值,以秒为单位。

就像我说的那样,功能上它完美无瑕,但我看不到用TextView值不断更新displayTime()对象的方法。任何人都可以建议尽可能简单的解决方案来实现这一目标吗?谢谢!

2 个答案:

答案 0 :(得分:0)

为此需要使用Timer类。

ActionListener timerTask = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
    lblTime.setText("Set your time here");     
        }
    };
Timer timer = new Timer(500, timerTask);
timer.start();

用于定时器类信息和API

  1. Class Timer API

  2. How to Use Swing Timers

答案 1 :(得分:0)

最简单的方法可能是使用Handler

private Handler h = new Handler();
private Runnable update = new Runnable() {
    void run() {
        // update the time in the text view here
        h.postDelayed(this, 1000); // reschedule the update in 1 sec
    }
};

// to start the update process
h.postDelayed(update, 0); // run the update the first time
相关问题