0

I'm trying to implement a very simple stopwatch widget in my Android activity such that the user can hit start/reset to start the timer, and stop to stop it. All of the functionality is there, but I can't seem to find a way to constantly display the value of this stopwatch.

I'm currently using a custom object that stores a long value representing the time the Stopwatch object was created, a constructor that sets this long value to the current time, and a displayTime method that returns the a double value representing the current time in seconds by subtracting the current time from the original time and divides by 1000.0.

Like I said, functionally it's flawless, but I can't see a way to constantly update a TextView object with the value of displayTime(). Can anyone suggest as simple of a solution as possible to accomplish this? Thank you!

Argus9
  • 1,863
  • 4
  • 26
  • 40

2 Answers2

0

You need to use Timer class for this purpose.

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

For Timer Class Information and API

  1. Class Timer API

  2. How to Use Swing Timers

Smit
  • 4,685
  • 1
  • 24
  • 28
0

The easiest way is probably to use a 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
Henry
  • 42,982
  • 7
  • 68
  • 84