2013-07-27 70 views
0

我想创建一个textedit字段,用户只输入一个日期(没有时间)。日期将存储在MY SQL中。用最少量的验证来做到这一点最好的方法是什么?有没有像日期内置的文本字段,以保持适当的格式?如何在android中以编程方式创建日期的文本编辑器?

我有这样的:

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+(即第7版)

有谁知道的工作?

感谢

+0

我真的建议你尝试在一些xml文件中定义它,并在必要时加载它。并测试一些其他输入类型,如数字/电话等 –

+0

我需要动态地插入它们,因为用户可以更改他们的数据。 – sneaky

+1

使用'InputType.TYPE_CLASS_DATETIME'而不是'InputType.TYPE_DATETIME_VARIATION_DATE'来显示数字键盘。用户输入后,您当然需要验证日期和格式。你可以使用'regex'。 – Vikram

回答

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问题。希望这可以帮助。

+0

它需要使用android 2.1。 – sneaky

+0

DatePicker类本身自API级别1开始。您可以使用AlertDialog.Builder创建对话框,并将其内容视图设置为DatePicker实例。 (或者,使用ActionBarSherlock你可以使用SherlockDialogFragment并将DatePicker放在那里) – Karakuri

+0

@Karakuri是对的。你可以在android 2.1中使用它。正如他正确地提到的,你也可以去做ActionBarSherlock。 –

相关问题