我想创建一个textedit字段,用户只输入日期(没时间)。日期将存储在MY SQL
中。什么是用最少的验证来做到这一点的最佳方法?是否有类似日期的内置文本字段,使其保持正确的格式?
我有这个:
public static void AddEditTextDate(Context context, LinearLayout linearlayout, String text, int id) {
EditText edittext = new EditText(context);
edittext.setInputType(InputType.TYPE_DATETIME_VARIATION_DATE);
edittext.setText(text);
edittext.setId(id);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
edittext.setLayoutParams(params);
linearlayout.addView(edittext);
}
但是当我尝试输入它时,它看起来像普通的键盘。我希望它默认进入数字键盘或其他东西......
编辑:需要使用android 2.1+(即v7)
有人知道吗?
由于
答案 0 :(得分:2)
你说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?
我想到了一种方法,您可能不需要检查用户输入的日期格式的任何验证。您可以点击EditText
框拨打DatePickerDialog。然后用户可以使用它选择日期。用户选择日期后,您可以使用所选日期更新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()));
}
来源:This回答Datepicker: How to popup datepicker when click on edittext问题。希望这可以帮助。