Android:如何在DatePickerFragment上禁用未来几天

时间:2017-01-24 08:28:48

标签: java android android-datepicker

我在android中使用DatePickerFragment创建了一个日期选择器。

以下是我的代码,

@OnClick(R.id.add_info_food_date_edit)
public void setDate() {

    DatePickerFragment datePickerFragment = new DatePickerFragment();
    datePickerFragment.setCallbackListener(new DatePickerFragment.onDatePickerListener() {
        @Override
        public void onDataSet(int year, int month, int day) {

            int currentMonth = 0;

            if (month == 0) {
                currentMonth = 1;
            } else if (month == 1) {
                currentMonth = 2;
            } else if (month == 2) {
                currentMonth = 3;
            } else if (month == 3) {
                currentMonth = 4;
            } else if (month == 4) {
                currentMonth = 5;
            } else if (month == 5) {
                currentMonth = 6;
            } else if (month == 6) {
                currentMonth = 7;
            } else if (month == 7) {
                currentMonth = 8;
            } else if (month == 8) {
                currentMonth = 9;
            } else if (month == 9) {
                currentMonth = 10;
            } else if (month == 10) {
                currentMonth = 11;
            } else if (month == 11) {
                currentMonth = 12;
            } else if (month == 12) {

            }

            dateEditText.setText(day + "/" + currentMonth + "/" + year);
        }
    });

    DialogFragment datePicker = datePickerFragment;

    datePicker.show(getSupportFragmentManager(), "datePicker");
}

现在我想在不破坏此代码的情况下禁用此datepicker中的未来日期。我仍然没有对这一变化有任何好的想法。我怎样才能做到这一点。

有任何想法吗?

1 个答案:

答案 0 :(得分:1)

将setMaxDate设为当前日期

datePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

更新

DialogFragment newFragment = datePickerFragment;
newFragment.show(getFragmentManager(), "datePicker");
getFragmentManager().executePendingTransactions();     // commits the show method from above
DatePickerDialog dialog = (DatePickerDialog) newFragment.getDialog();
DatePicker datePicker = (DatePicker) dialog.getDatePicker();
Date date = new Date();
datePicker.setMaxDate(date.getTime());