How to disable certain dates in the Android Date Picker dialog?

試著忘記壹切 提交于 2019-12-17 14:01:20

问题


I am using default Android DatePickerDialog which contains android.widget.DatePicker.

Does anybody know how to disable or make certain dates unselectable?

I know DatePicker allows to setMinDate() and setMaxDate() but it doesn't allow to disable specific dates in the middle.

e.g. on this picture would like to disable date 18, 26, etc:


回答1:


That is not a built in behavior - you would have to use a custom date picker.




回答2:


I got a method by using custom datepicker. First we need to take the date as a string and then convert it into date object and then the date is converted to calendar object. At last by using setDisabledDays(calenderobj). We can disable it. The code is as follows.

 SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                String a = "26-07-2017";
                java.util.Date date = null;
                try {
                    date = sdf.parse(a);
                    MainActivity obj = new MainActivity();
                    calendar = obj.dateToCalendar(date);
                    System.out.println(calendar.getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                List<Calendar> dates = new ArrayList<>();
                dates.add(calendar);
                Calendar[] disabledDays1 = dates.toArray(new Calendar[dates.size()]);
                dpd.setDisabledDays(disabledDays1);
                }


    private Calendar dateToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }


来源:https://stackoverflow.com/questions/34727244/how-to-disable-certain-dates-in-the-android-date-picker-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!