在Android日期选择器中禁用特定日期

时间:2016-02-24 10:15:28

标签: android datepicker

我使用了datePicker,我可以通过以下代码禁用今天的最后几天和30天后的后几天:

DatePickerDialog datePicker = new DatePickerDialog();

             Calendar calender = Calendar.getInstance();
             long today = calender.getTimeInMillis();
             final long oneDay = 24 * 60 * 60 * 1000L;

             Date previousDays = new Date(today - 1000);
             datePicker.setMinDate(DateToCalendar(previousDays));

             Date nextMonth = new Date(today + 30 * oneDay);
             datePicker.setMaxDate(DateToCalendar(nextMonth));

如果我想每个星期五禁用星期五,我该怎么做?

6 个答案:

答案 0 :(得分:11)

您可以使用此库Material Date Time Picker,您可以在此设置显示特定日期的选项,例如:

datePicker.setSelectableDays(Calendar[] days)

并传递Calendar数组作为包含所有可选日期的参数。

答案 1 :(得分:4)

使用android datepicker是不可能的,你需要为自己创建一个自定义选择器。见MaterialDateTimePicker

要禁用星期日,您必须像这样传递数组

      GregorianCalendar g1=new GregorianCalendar();
      g1.add(Calendar.DATE, 1);
      GregorianCalendar gc = new GregorianCalendar();
      gc.add(Calendar.DAY_OF_MONTH, 30);
       List<Calendar> dayslist= new LinkedList<Calendar>();
Calendar[] daysArray;
Calendar cAux = Calendar.getInstance();
while ( cAux.getTimeInMillis() <= gc.getTimeInMillis()) {
    if (cAux.get(Calendar.DAY_OF_WEEK) != 1) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(cAux.getTimeInMillis());
        dayslist.add(c);
    }
    cAux.setTimeInMillis(cAux.getTimeInMillis() + (24*60*60*1000));
}
daysArray = new Calendar[dayslist.size()];
for (int i = 0; i<daysArray.length;i++)
{
    daysArray[i]=dayslist.get(i);
}
datePickerDialog.setSelectableDays(daysArray);

答案 2 :(得分:3)

使用自定义DatePickerDialog

在build.gradle

中添加
  

编译'com.wdullaer:materialdatetimepicker:3.5.1'

实施

  你的班级

DatePickerDialog.OnDateSetListener

并导入

  

导入com.wdullaer.materialdatetimepicker.date.DatePickerDialog; 而不是'import android.app.DatePickerDialog;'

并添加此方法

 private void showDatePicker() { 

    Calendar calendar = Calendar.getInstance();

    DatePickerDialog dpd = DatePickerDialog.newInstance(
            this,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
    );
    dpd.show(getActivity().getFragmentManager(), "DatePickerDialog");

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    String a = "07-03-2018"; // example

    java.util.Date date = null;

    try {
        date = sdf.parse(a);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    calendar = dateToCalendar(date);
    System.out.println(calendar.getTime());

    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;
    }




@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

    String date = dayOfMonth+"/"+(monthOfYear+1)+"/"+year;
    textview.setText(date);

}
  

调用showDatePicker()。

多天

更改此

     String[] holidays = {"07-03-2018","05-03-2018","10-03-2018"};

    java.util.Date date = null;

    for (int i = 0;i < holidays.length; i++) {

        try {
            date = sdf.parse(holidays[i]);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        calendar = dateToCalendar(date);
        System.out.println(calendar.getTime());

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

答案 3 :(得分:2)

访问https://stackoverflow.com/a/44692231/6631959         最好的方法,易于理解......         如果你正在寻找如何禁用指定的日期,那就更好了。         不是循环过程。给出任何确切的日期并禁用它。

代码是HEre ::

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;
        }

答案 4 :(得分:0)

尝试 Android Material Date和Timepicker

来源Link

禁用周日和周六。

enter image description here

您还可以使用 setDisabledDays()方法禁用任何特定日期

            //Disable all SUNDAYS and SATURDAYS between Min and Max Dates
            for (Calendar loopdate = min_date_c; min_date_c.before(max_date_c); min_date_c.add(Calendar.DATE, 1), loopdate = min_date_c) {
                int dayOfWeek = loopdate.get(Calendar.DAY_OF_WEEK);
                if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) {
                    Calendar[] disabledDays =  new Calendar[1];
                    disabledDays[0] = loopdate;
                    datePickerDialog.setDisabledDays(disabledDays);
                }
            }

答案 5 :(得分:0)

由于这里接受的答案依赖于 com.wdullaer 的自定义实现,我想提出另一个解决方案,我刚刚使用标准 MaterialDatePicker 和自定义 DateValidator 实现:

            // Create a custom date validator to only enable dates that are in the list
        val customDateValidator = object: CalendarConstraints.DateValidator {
            override fun describeContents(): Int {  return 0  }
            override fun writeToParcel(dest: Parcel?, flags: Int) {    }
            override fun isValid(date: Long): Boolean {

                listOfPossibleDatesAsLong.forEach {
                    val itemDateTime = Calendar.getInstance()
                    itemDateTime.timeInMillis = it

                    val dateDateTime = Calendar.getInstance()
                    dateDateTime.timeInMillis = date

                    if(itemDateTime.get(Calendar.YEAR) == dateDateTime.get(Calendar.YEAR)
                        && itemDateTime.get(Calendar.MONTH) == dateDateTime.get(Calendar.MONTH)
                        && itemDateTime.get(Calendar.DAY_OF_MONTH) == dateDateTime.get(Calendar.DAY_OF_MONTH))
                        return true
                }
                return false
            }
        }

除了 CalendarConstraints 中的其他约束,现在只需设置 customDateValidator,这也可以与 setStart(...) 和 setEnd(...) 一起使用

        // Build constraints.
        val constraintsBuilder =
            CalendarConstraints.Builder().apply {
                    // other constraints
                    setValidator(customDateValidator)
                }
            }

然后定义datePicker并显示

        val datePicker =
            MaterialDatePicker.Builder.datePicker()
                .setTitleText("Select date")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .setCalendarConstraints(constraintsBuilder.build())
                .build()

        datePicker.addOnPositiveButtonClickListener {
            // Respond to positive button click...
        }

        datePicker.show(parentFragmentManager, "tag")

我需要承认,我不明白如果不正确实施 describeContents 和 writeToParcel 是否会对任何事情产生负面影响,也许这可以在这里讨论。但是,就我而言,这非常有效。