如何在Android DatePicker中禁用以前的日期?

时间:2015-12-07 13:29:52

标签: java android android-intent android-calendar android-datepicker

我想在DatePicker停用过去的日期并仅显示当前和未来的日期...我使用下面的代码,但这也会显示过去的日期,请提供所需的更改。

date_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
             Calendar calendar = Calendar.getInstance();
                mDay = calendar.get(Calendar.DAY_OF_MONTH);
                mMonth = calendar.get(Calendar.MONTH);
                mYear = calendar.get(Calendar.YEAR);

            OnDateSetListener callBack = new OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    Calendar calender_check = Calendar.getInstance(Locale.getDefault());
                    calender_check.set(Calendar.YEAR, year);
                    calender_check.set(Calendar.MONTH, monthOfYear);
                    calender_check.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy");
                    Date date2 =calender_check.getTime();


                    updatedate(sdf2.format(date2),originalFormat.format(date2));
                    Log.d("Date >>>>", ""+date2);

                    Log.d("sel_date", sdf2.format(date2));

                    date_btn.setText(sdf2.format(date2));
                }
            };
            DatePickerDialog dialog = new DatePickerDialog(Class.this, callBack, mYear, mMonth, mDay);

            dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(which == DialogInterface.BUTTON_NEGATIVE) {
                   // Log.i(TAG, "Cancel");
                    //isCancelled = true;
                    dialog.dismiss();}
                }
            });
            dialog.setCancelable(false);
            dialog.show();

        }
    });

2 个答案:

答案 0 :(得分:2)

在创建DatePickerDialog之前,设置最小日期然后显示它。

DatePickerDialog datePickerDialog = new  DatePickerDialog(MainActiviy.this,date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),   myCalendar.get(Calendar.DAY_OF_MONTH));
SimpleDateFormat simpledateformate = new SimpleDateFormat("dd/MM/yyyy");
Date date = simpledateformate.parse("21/12/2012");
datePickerDialog.getDatePicker().setMinDate(d.getTime());
datePickerDialog.show();

答案 1 :(得分:1)

您可以尝试这样的代码:

DatePicker view; final long time = System.currentTimeMillis() - 1; //Set min time to now view.setMinDate(time);