Restructuring DatePickerDialog

If you want to restrict your user not to enter date lesser then the current date from DatePickerDialog then you can use the below code as such :

try {
            DateTime dt = new DateTime(desiredDate, DateTimeZone.UTC);

            DatePickerDialog selectDatePicker = new DatePickerDialog(this, mDateSelectedListener, dt.getYear(),
                    dt.getMonthOfYear() - 1, dt.getDayOfMonth());
            java.lang.reflect.Field mDatePickerField = selectDatePicker.getClass().getDeclaredField("mDatePicker");
            mDatePickerField.setAccessible(true);
            DatePicker mDatePicker = (DatePicker) mDatePickerField.get(selectDatePicker);

            mDatePicker.init(dt.getYear(), dt.getMonthOfYear() - 1, dt.getDayOfMonth(),
                    new OnDateChangedListener() {

                        @Override
                        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                                int dayOfMonth) {

                            if (isDateAfter(view)) {
                                Calendar mCalendar = Calendar.getInstance();
                                view.init(mCalendar.get(Calendar.YEAR),
                                        mCalendar.get(Calendar.MONTH),
                                        mCalendar.get(Calendar.DAY_OF_MONTH), this);
                            }
                        }

                        private boolean isDateAfter(DatePicker tempView) {
                            Calendar mCalendar = Calendar.getInstance();
                            Calendar tempCalendar = Calendar.getInstance();
                            tempCalendar.set(tempView.getYear(), tempView.getMonth(),
                                    tempView.getDayOfMonth(), 0, 0, 0);
                            if (tempCalendar.before(mCalendar))
                                return true;
                            else
                                return false;
                        }
                    });
            selectDatePicker.show();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
Advertisements