Android development Tip 2-avoid date verification in EditText
Developers know that the data in the verification form is annoying and error-prone, as is the verification in the Date input box. We can develop a Button that looks the same as EditText. After you click this Button, a DatePicker control is displayed.
To implement the above idea, you need to change the default background of the Button control to the background of EditText.
Let's take a look at main. xml:
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); // pop-up dialog box});} private DatePickerDialog. onDateSetListener mDateSetListener = new DatePickerDialog. onDateSetListener () {// listener date setting event @ Overridepublic void onDateSet (DatePicker view, int year, int monthOfYear, int dayOfMonth) {mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay ();} private void updateDisplay () {// set to display mButton. setText (new StringBuilder (). append (mYear ). append ("-"). append (mMonth + 1 ). append ("-"). append (mDay) ;}}; protected dited onCreateDialog (int id) {switch (id) {case DATE_DIALOG_ID: return new DatePickerDialog (this, mDateSetListener, mYear, mMonth, mDay ); default: break;} return null ;}}
Running instance:
Summary
1.Android: background = "@ android: drawable/edit_text": displays the Button as an EditText style;
2. Pay attention to the method of the create date dialog box.