Developers all know that validating the data in a form is annoying and error-prone, as does the validation of date input boxes. We can develop a look that looks like a edittext button, and when you click the button, a DatePicker control is displayed.
To implement the above idea, you need to change the default background of the button control to a edittext background.
Take a look at Main.xml:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:orientation= "vertical" > <button android:id= "@+id/btn_date" android:layout_width = "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizontal" android:background= "@android:d rawable/edit_text" android:gravity= "center" android:text= "Choose Birthdays" > <!-- android:background= "@android:d rawable/edit_text" background set to EditText style- </button></ Linearlayout>
Then let's take a look at the Mainactivity.java file:
Package Com.yayun.edittextdatedemo;import Android.app.activity;import Android.app.datepickerdialog;import Android.app.dialog;import Android.os.bundle;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.datepicker;public class Mainactivity extends Activity {private Button mbutton;static final int date_dialog_id=0;private int myear;private int mmonth;private int mday;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main) mbutton= (Button) Findviewbyid (r.id.btn_date); Mbutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {showDialog (date_dialog_id);//Popup Dialog}}); Private Datepickerdialog.ondatesetlistener mdatesetlistener=new Datepickerdialog.ondatesetlistener () {// Listener date set event @overridepublic void Ondateset (DatePicker view, int year, int monthofyear, int dayofmonth) {myear=year;mmonth= Monthofyear;mday=dayofmonth;updateDisplay ();} private void Updatedisplay () {//settings display Mbutton.settext (new StringBuilder (). Append (Myear). Append ("-"). Append (mmonth+1) . Append ("-"). Append (Mday));}; protected Dialog oncreatedialog (int id) {switch (ID) {Case date_dialog_id:return new Datepickerdialog (This, Mdatesetlistener, Myear, Mmonth, mday);d Efault:break;} return null;}}
Running an instance:
Summarize
1.android:background= "@android:d rawable/edit_text" to display the button as a edittext style;
2. Note the method of the Create Date dialog box.
Android Development Tips Two--avoid validating dates in EditText