如何限制 DatePickerDialog 选择过去 2-12 年或当前日期 0-2 年的日期?
我在活动中有 DatePickerDialog,用于获取儿童和婴儿的出生日期。儿童年龄为(2-12 岁),婴儿年龄为(0-2 岁)。如果我通过 1,那么年龄限制应该是(2-12 岁),如果我通过 2,年龄限制应该是(0-2 岁)。
我可以做些什么来在我的日历中获得这个功能?
我的日历代码是:
date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
dateofBirth.setText(sdf.format(myCalendar.getTime()));
}
};
dateofBirth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
}
});
public Dialog onCreateDialog(int id) {
final Calendar now = Calendar.getInstance();
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this, date,myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)){
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){
if (year > now.get(Calendar.YEAR))
view.updateDate(myCalendar
.get(Calendar.YEAR), myCalendar
.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
if (monthOfYear > now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
view.updateDate(myCalendar
.get(Calendar.YEAR), myCalendar
.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
if (dayOfMonth > now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) &&
monthOfYear == now.get(Calendar.MONTH))
view.updateDate(myCalendar
.get(Calendar.YEAR), myCalendar
.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
}
};
return _date;
}
return null;
}