Ce qui suit a fonctionné pour moi.
Tout d'abord, dans onCreate:
pickStartTime = (TimePicker)findViewById(R.id.StartTime);
pickStartTime.setOnTimeChangedListener(mStartTimeChangedListener);
Définissez OnTimeChangedListener:
private TimePicker.OnTimeChangedListener mStartTimeChangedListener =
new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
updateDisplay(view, startDate, hourOfDay, minute);
}
};
Null OnTimeChangedListener (expliqué dans les commentaires dans updateDisplay ci-dessous):
private TimePicker.OnTimeChangedListener mNullTimeChangedListener =
new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
}
};
private void updateDisplay(TimePicker timePicker, Date date, int hourOfDay, int minute) {
// do calculation of next time
int nextMinute = 0;
if (minute >= 45 && minute <= 59)
nextMinute = 45;
else if(minute >= 30)
nextMinute = 30;
else if(minute >= 15)
nextMinute = 15;
else if(minute > 0)
nextMinute = 0;
else {
nextMinute = 45;
}
// remove ontimechangedlistener to prevent stackoverflow/infinite loop
timePicker.setOnTimeChangedListener(mNullTimeChangedListener);
// set minute
timePicker.setCurrentMinute(nextMinute);
// hook up ontimechangedlistener again
timePicker.setOnTimeChangedListener(mStartTimeChangedListener);
// update the date variable for use elsewhere in code
date.setMinutes(nextMinute);
}