private void findViewsById() {
fromDateEtxt = (EditText) findViewById(R.id.dobET);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
}
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar dob = Calendar.getInstance();
dob.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(dob.getTime()));
Calendar today = Calendar.getInstance();
dob.set(year, monthOfYear, dayOfMonth);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
if(age >= 18) {
fromDateEtxt.setText(dateFormatter.format(dob.getTime()));
fromDateEtxt.setError(null);
}
else {
fromDateEtxt.setText("");
fromDateEtxt.setError("Age must be above 18 years.");
}
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
在我们想要的例子中,日历将仅显示出生日期的18年以上。如果用户少于18年,我使用fromDateEtxt.setError(“年龄必须超过18年。”)。
答案 0 :(得分:0)
/**
* Method to extract the user's age from the entered Date of Birth.
*
* @param DoB String The user's date of birth.
*
* @return ageS String The user's age in years based on the supplied DoB.
*/
private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
答案 1 :(得分:0)
您可以使用setMaxDate()
限制用户Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -18);
DatePickerDialog dpd = new DatePickerDialog(this, null, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
dpd.getDatePicker().setMaxDate(cal.getTime().getTime());
dpd.show();
答案 2 :(得分:0)
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
dob = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
dob.add(Calendar.YEAR, -18);
fromDatePickerDialog.getDatePicker().setMaxDate(dob.getTime().getTime());
dob.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(dob.getTime()));
dob.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(dob.getTime()));
}
}, dob.get(Calendar.YEAR), dob.get(Calendar.MONTH),
dob.get(Calendar.DAY_OF_MONTH)); }