0

我想在DatePicker中禁用我過去的日期,並只顯示當前和未來的日期...我使用下面的代碼,但這也會顯示過去的日期,請建議所需的更改。如何在Android 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(); 

     } 
    }); 

回答

0

你或許可以嘗試像這樣的代碼:

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

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(); 
+0

haiiü可以編輯我code..pls – learner

+0

這行代碼後:DatePickerDialog對話框=新DatePickerDialog(Class.this回調,mYear,mMonth,MDAY);只需添加這三行:SimpleDateFormat simpledateformate = new SimpleDateFormat(「dd/MM/yyyy」); 日期date = simpledateformate.parse(「2012年12月12日」); datePickerDialog.getDatePicker()。setMinDate(d.getTime());並運行它... – santoXme

+0

thamk u..but它顯示d無法解析..可以幫助 – learner

相關問題