在Android中限制日期选择器以及将来的日期

时间:2015-03-30 09:30:38

标签: android date datepicker

我正在开发一个Android应用程序,我在其中使用日期选择器来选择日期。我将它用于出生日期,现在我想限制用户不要选择任何将来的日期。

我的代码如下:

private void checkDate(){
        final Calendar c = Calendar.getInstance();
        mSelectedYear = c.get(Calendar.YEAR);
        mSelectedMonth = c.get(Calendar.MONTH);
        mSelectedDay = c.get(Calendar.DAY_OF_MONTH);
    }

txtDateOfBirth.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(mDATE_PICKER_ID);
            }
        });


    @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case mDATE_PICKER_ID:
                return new DatePickerDialog(this, pickerListener, mSelectedYear,mSelectedMonth, mSelectedDay);
            }
            return null;
        }

        private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int selectedyear,
                    int selectedmonth, int selectedday) {
                mSelectedYear = selectedyear;
                mSelectedMonth = selectedmonth;
                mSelectedDay = selectedday;

                txtDateOfBirth.setText(new StringBuilder().append(mSelectedMonth + 1).append("-").append(mSelectedDay).append("-").append(mSelectedYear).append(" "));
                mDateSelected = new StringBuilder().append(mSelectedDay).append("-").append(mSelectedMonth + 1).append("-").append(mSelectedYear).toString();
            }

        };

1 个答案:

答案 0 :(得分:2)

使用此选项可将对话框限制为当前日期:

datePicker.getDatePicker().setMaxDate(new Date().getTime());

但请记住,它只适用于API 11或更高版本