Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i change the Android TimePicker minute intervals?

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.

like image 428
JeanBrand Avatar asked Dec 12 '22 15:12

JeanBrand


2 Answers

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();
    }
}
like image 191
Alex Wang Avatar answered Dec 14 '22 06:12

Alex Wang


all relative answer need you to set an OnTimeChangedListener. My resolution is that you extends android TimePicker,and modify the constructor of it:

    // minute
    mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
    mMinuteSpinner.setMinValue(0);
    mMinuteSpinner.setMaxValue(3);
    mMinuteSpinner.setDisplayedValues(new String[]{"0", "15", "30", "45"});
    mMinuteSpinner.setOnLongPressUpdateInterval(100);
    mMinuteSpinner.setFormatter(NumberPicker.getTwoDigitFormatter());

so you can have the interval you want.

like image 34
01.sunlit Avatar answered Dec 14 '22 06:12

01.sunlit