An Android Stopwatch TextView

The Chronometer class which is part of the standard Android SDK is useful for counting the number of milliseconds from a point in time. It does not however allow pause and restart like a normal stopwatch. I needed this type of functionality for my app, so I have extended Chronometer to provide this:

public class StopWatch extends Chronometer {
    private long elapsedBeforePause;

    public StopWatch(Context ctx) {
        super(ctx);
    }

    public StopWatch(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }

    public void startClock() {
        setBase(SystemClock.elapsedRealtime());
        super.start();
    }

    public long stopClock() {
        long result = SystemClock.elapsedRealtime() - getBase();
        super.stop();
        return result;
    }

    public void pauseClock() {
        elapsedBeforePause = stopClock();
    }

    public void restartClock() {
        setBase(SystemClock.elapsedRealtime() - elapsedBeforePause);
        elapsedBeforePause = 0;
        super.start();
    }

}


Pretty straightforward stuff, but it was useful to work out how to extend a TextView and use the subclass in my code.

You can just include this StopWatch in your layout files like this:







Change the package name to whatever you decide to use (or leave it as it is if you like).

Call the startClock() method in the onCreate() of the activity that is going to contain the timer and then put an event on a button to stop the clock. A ToggleButton is the best way to work the pause/restart feature. Add the ToggleButton to your activity. Give it a standard OnClickListener.onClick() and check the status of its isChecked() method to decide whether to call restartClock() or pauseClock().

Let me know if you get any use out of this. 


Comments

Popular posts from this blog

Building a choropleth map for Irish agricultural data

Early Stopping with Keras

AutoCompleteTextView backed with data from SQLite in Android