Search code examples
androiddatepickerandroid-datepickerandroid-date

Set minimum Date in DatePickerDialog


I want to set min date of my DatePicker Dialog from tomorrow day. Example if today is 30 April 2015, it should start with 1 May 2015.

My code:

final Calendar myCalendar = Calendar.getInstance();

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        }
    };

    startDate.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

        DatePickerDialog dialog = new DatePickerDialog(
                    SomeClassName.this, date, myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar
                            .get(Calendar.DAY_OF_MONTH));
        dialog.show();
        dialog.getDatePicker().setMinDate(
                        System.currentTimeMillis() - 10000);
    }});

I am facing 2 problems respectively.

  1. The date range starts from current date i.e 30 April 2015.

  2. Whatever date I choose by scrolling the datepicker, only 30 April 2015 is being set.

Note: the datepicker dialog pops on touch event of an editText Box.


Solution

  • public class DatePickerFragment extends DialogFragment implements
                DatePickerDialog.OnDateSetListener {
    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                // Use the tommorrow date as the default date in the picker
                final Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_MONTH, 1);
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DAY_OF_MONTH);
    
                // Create a new instance of DatePickerDialog and return it
                DatePickerDialog dp = new DatePickerDialog(getActivity(), this, year, month, day);
                dp.getDatePicker().setMinDate(c.getTimeInMillis());
                return dp;
            }
    
            public void onDateSet(DatePicker view, int year, int month, int day) {
                // Do something with the date chosen by the user
            }
        }
    

    Showing the date picker:

    public void showDatePickerDialog() {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
    

    For more information visit: http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker