禁用datepicker中的未来日期选择

时间:2013-02-22 09:25:24

标签: android alertdialog android-datepicker

这是我的日期选择器对话框代码。我想在日期选择器对话框中禁用将来的日期选择。

有人可以提出建议吗?

@Override
protected Dialog onCreateDialog(int id)
{
    // TODO Auto-generated method stub
    switch(id)
    {
        case 1:
            Calendar cal=Calendar.getInstance();
            Toast.makeText(DateActivity.this, "- onCreateDialog -", Toast.LENGTH_LONG).show();
            return new DatePickerDialog(this,myDateSetListener,cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_YEAR));

        default:
            return null;
    }
}

private DatePickerDialog.OnDateSetListener myDateSetListener = new DatePickerDialog.OnDateSetListener()
{
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        // TODO Auto-generated method stub
        String date = "Year: " + String.valueOf(year) + "\n"
                    + "Month: " + String.valueOf(monthOfYear+1) + "\n"
                    + "Day: " + String.valueOf(dayOfMonth);

        Toast.makeText(DateActivity.this, date,Toast.LENGTH_LONG).show();
    }
};

3 个答案:

答案 0 :(得分:1)

OnDateChangedListener设置为DateTimePicker,其中

onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)

检查日期是否在您允许的范围内,如果不是,请使用您允许的最长日期致电view.updateDate

答案 1 :(得分:1)

在onCreateDialog里面加上这个方法,解决了这个问题,因为将来的日期必须不是选择日期选择器dailog,

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        DatePickerDialog mDatePickerDialog = new DatePickerDialog(this, mDateSetListener, intYear, intMonth, intDay);
        mDatePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); // Important as Future date not selection
        return mDatePickerDialog;
    }
    return null;
}

答案 2 :(得分:-1)

yourdatepicker.getDatePicker()setMaxDate(System.currentTimeMillis的());