Friday, January 11, 2013

TimePickerDialog - 15 Minutes Interval


Default TimePickerDialog having 1 minute interval changes, how make this by 15 or 30 minutes.
in a very simple way, just create a customize TimePickerDialog class and override the onTimeChanged method of dialog
see below sample code
public class TimePickerDialogs extends TimePickerDialog{

 public TimePickerDialogs(Context arg0, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
  super(arg0, callBack, hourOfDay, minute, is24HourView);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
  // TODO Auto-generated method stub
  //super.onTimeChanged(arg0, arg1, arg2);
  if (mIgnoreEvent)
            return;
        if (minute%TIME_PICKER_INTERVAL!=0){
            int minuteFloor=minute-(minute%TIME_PICKER_INTERVAL);
            minute=minuteFloor + (minute==minuteFloor+1 ? TIME_PICKER_INTERVAL : 0);
            if (minute==60)
                minute=0;
            mIgnoreEvent=true;
            view.setCurrentMinute(minute);
            mIgnoreEvent=false;
        }
 }

 private final int TIME_PICKER_INTERVAL=15;
 private boolean mIgnoreEvent=false;
 
}
and called this class by this line of code in your activity class
new TimePickerDialogs(this, new TimePickerDialog.OnTimeSetListener(){

  @Override
  public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
  // TODO Auto-generated method stub
  StringBuilder output = new StringBuilder().append(selectedHour).append(":").append(selectedMinute);
         System.out.println(output.toString());
                }}, hour, minute, true).show();

8 comments:

  1. Thank you so much you saved my time!! :)

    ReplyDelete
  2. Thanks alot.................Ashwini

    ReplyDelete
  3. oh oh can no work in my code!

    ReplyDelete
  4. but while scrolling this shows the next increment by one even though the selection is reaching towards 15 durataion. is there any way to see this as 15, 30, 45 etc.

    ReplyDelete
  5. can you send me a complete example please not working here

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. 15 minute interval not showing. it display same as earlier.

    ReplyDelete