How do i change the Android TimePicker minute intervals?

JeanBrand picture JeanBrand · Apr 24, 2013 · Viewed 20.8k times · Source

I am writing an application where the user needs to specify a given point in time, but i can't seem to figure out how to set the minute values that the user can choose from, to only use increments of 5 instead of increments of 1.

Simply put, when the user scrolls through the available amounts, he/she must only see 0,5,10,15 etc.

Thank you in advance.

Answer

Alex Wang picture Alex Wang · Aug 28, 2015

To ensure you're compatible with API 21+, make sure your TimePicker has the following attribute:

android:timePickerMode="spinner"

Then here's how you can set an interval programmatically. This method falls back on the standard TimePicker if the minute field cannot be found:

private static final int INTERVAL = 5;
private static final DecimalFormat FORMATTER = new DecimalFormat("00");

private TimePicker picker; // set in onCreate
private NumberPicker minutePicker;

public void setMinutePicker() {
    int numValues = 60 / INTERVAL;
    String[] displayedValues = new String[numValues];
    for (int i = 0; i < numValues; i++) {
        displayedValues[i] = FORMATTER.format(i * INTERVAL);
    }

    View minute = picker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
    if ((minute != null) && (minute instanceof NumberPicker)) {
        minutePicker = (NumberPicker) minute;
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue(numValues - 1);
        minutePicker.setDisplayedValues(displayedValues);
    }
}

public int getMinute() {
    if (minutePicker != null) {
        return (minutePicker.getValue() * INTERVAL);
    } else {
        return picker.getCurrentMinute();
    }
}