如何不允许用户在datepicker中选择过去的日期?

时间:2012-02-29 06:08:30

标签: android

我想在用户选择datepicker中的过去日期时,它不应该接受昨天的日期。我的应用程序将提示消息通知用户不能选择少于当前日期。请指导我吗?...谢谢

mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            Button pickDate_btn = (Button) findViewById(R.id.pickDate);
            pickDate_btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        final Calendar now = Calendar.getInstance();
        mYear = now.get(Calendar.YEAR);
        mMonth = now.get(Calendar.MONTH);
        mDay = now.get(Calendar.DAY_OF_MONTH);

        updateDisplay();      

@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {

            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
        }
    }    

    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mDay).append("-")
                    .append(mMonth + 1).append("-")
                    .append(mYear).append(" "));
    }

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

    @Override
    public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                    // TODO Auto-generated method stub

            mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();

    //should add code here?             
                }
            };

2 个答案:

答案 0 :(得分:7)

从API级别11开始,有一种方法:

DatePicker.setMinDate(new Date().getTime())

或者,如果它不起作用(旧API),那么,

Date datePickerDate = // get the value here;
Date currentDate = new Date();
if (datePickerDate.before(currentDate)) {
  // error !
}

答案 1 :(得分:3)

我们无法设置任何限制DatePicker的属性来选择未过去的日期,但我们可以通过以下方式以编程方式执行:

if(dateObj1.before(dateObj2) || dateObj1.equals(dateObj2)){
//the program runs normally
}
else{

                new AlertDialog.Builder(PM_Edit.this)

                .setTitle("Wrong Data Input!")

                .setMessage("The end Date must be Before the start Date, please insert new Date values")

                .setNeutralButton("Ok",

                new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,

                int which) {

                }

                }).show();
            }