hour/minute picker for android countdown timer

Dan Quach picture Dan Quach · Sep 16, 2010 · Viewed 9.2k times · Source

I'm trying to implement something like a countdown timer that plays an alarm at 0. I want to be able to set the amount of time to wait before the timer goes off and I'm wondering if there's a UI widget or element that provides this kind of selection functionality.

Basically, does android have something like the iPhone's selection spinwheel? Or is there some type of timepicker that allows selection of an arbitrary number of hours and minutes? The timepicker widget in android has an unnecessary AM/PM label.

Do I need to implement my own custom UI to achieve this?

Answer

Arnoud picture Arnoud · Nov 2, 2010

You can use the default TimePickerDialog and override the onTimeChanged method to update the title yourself:

public class DurationPickerDialog extends TimePickerDialog {

    public DurationPickerDialog(Context context, int theme,
        OnTimeSetListener callBack, int hour, int minute) {
        super(context, theme, callBack, hour, minute, true);
        updateTitle(hour, minute);
    }

    public DurationPickerDialog(Context context, OnTimeSetListener callBack,
        int hour, int minute) {
        super(context, callBack, hour, minute, true);
        updateTitle(hour, minute);
    }

    @Override
    public void onTimeChanged(TimePicker view, int hour, int minute) {
        super.onTimeChanged(view, hour, minute);
        updateTitle(hour, minute);
    }

    public void updateTitle(int hour, int minute) {
        setTitle("Duration: " + hour + ":" + formatNumber(minute));
    }

    private String formatNumber(int number) {
        String result = "";
        if (number < 10) {
            result += "0";
        }
        result += number;

        return result;
    }
}