2013-07-27 71 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。 –

相關問題