我在我的申请中偶尔使用日期选择器。我希望我的日期选择器显示一些限制后的日期。我使用以下代码: -
@Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
datePickerDialogDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
date = selectedDate;
activitySignUpDateEditText.setText(new StringBuilder().append(date));
activitySignUpMonthEditText.setText(new StringBuilder().append(month + 1));
activitySignUpYearEditText.setText(new StringBuilder().append(year));
}
};
return new DatePickerDialog(this, datePickerDialogDateSetListener, year, month, date);
default:
return null;
}
}
在某个地方,我希望日期选择器显示从当前日期起18年后的最长日期。某处最小日期为当前日期。我搜索了很多,但没有找到任何满意的答案。我知道setMaxDate()& setMinDate()日期选择器的方法,但当我尝试使用它时,我无法在我的编辑文本上设置选定的日期。任何帮助都会很明显。提前致谢。
答案 0 :(得分:1)
您可以尝试替换此行:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
由那些人:
DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();
Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;
以同样的方式设置最小日期
DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();
Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMinDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;
答案 1 :(得分:1)
要将最长日期设置为18年,以下代码段将完成此任务:
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog = new DatePickerDialog(this, datePickerListener, year - 18, month, day);
//For setting minimum date as Current Date
//dateDialog.getDatePicker().setMinDate(c.getTimeInMillis ());
//For setting maximum date as 18 years back
c.set(year - 18, month, day);
dateDialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dateDialog;
由于MaxDate不能小于MinDate,因此当MaxDate设置为18年后,不应将MinDate设置为当前日期。
希望它对你有用。