2013-01-03 32 views
0

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

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

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

+0

您需要使用Timer类来达到此目的。 – Smit

+0

可能的重复:http://stackoverflow.com/questions/4597690/android-timer-how – Foggzie

+0

正是我在找什么,谢谢!回复作为答案,以便我可以批准并向上投票。 – Argus9

回答

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(); 

对于Timer类信息和API

  1. Class Timer API

  2. How to Use Swing Timers

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