-->

Android DatePicker/Dialog displaying incorrect mon

2019-02-22 20:27发布

问题:

I'm using the DatePickerDialog and the DatePicker to set a specific range.

datePicker.setMinDate(minDate);
datePicker.setMaxDate(maxDate);

If my min/max - dates are in the range of one month (eg.: 7.2.2014 - 27.2.2014), i still get the neighbour months displayed in the dialog (Jan, Mar). If i choose the last month (Jan), the dialog automatically swaps to the minDate and the month switches back to Feb. Same thing for the future month.

Is there a way to fix this, so that i only get the months displayed, which are in my range?

回答1:

In Android Month start from zero.....

So u have to use zero for january and 11 for December



回答2:

i have the same bug (and many peoples on StackOverflow)

my solution:

    monthPickerFrom =(DatePicker)mDialogView.findViewById(R.id.monthPickerFrom);
    HideDay(monthPickerFrom);
    Calendar currentDate = Calendar.getInstance();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2007);
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    monthPickerFrom.setMinDate(cal.getTimeInMillis());

    cal.set(Calendar.YEAR, currentDate.get(Calendar.YEAR));
    cal.set(Calendar.MONTH, currentDate.get(Calendar.MONTH));
    monthPickerFrom.setMaxDate(cal.getTimeInMillis());

    monthPickerFrom.init(currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), 1, new DatePicker.OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            ...
    });