你说Whats the best way to do this with the least amount of validation? Is there like a built in textfield for dates that keeps it in the proper format?
我想到了一种方法,使用它您可能不需要检查用户输入的日期格式的任何验证。您可以在单击框时调用DatePickerDialog 。EditText
然后用户可以使用它来选择日期。用户选择日期后,您可以使用所选日期更新您的 EditText。通过这种方式,您可以减少验证输入日期格式的工作量,并且用户可以轻松直观地选择日期。你可能是这样的:
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
//When the editText is clicked then popup the DatePicker dialog to enable user choose the date
edittext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(new_split.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
// Call this whn the user has chosen the date and set the Date in the EditText in format that you wish
private void updateLabel() {
String myFormat = "MM/dd/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
edittext.setText(sdf.format(myCalendar.getTime()));
}
资料来源:日期选择器上的这个答案:点击编辑文本问题时如何弹出日期选择器。希望这可以帮助。