Date picker in Android

Viewed 75011

Can any one post sample code for a simple date picker in Android.

If date picker is not possible in Android, an option to choose a date is needed.

8 Answers

To use DatePicker add below source code in your OnCreate of Activity.

PS: make sure that android:focusable="false" should be provided for your EditText.

// Edittext in your layout file
date = (EditText) findViewById(R.id.date);
// onclick on edit text
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR); // current year
    int mMonth = c.get(Calendar.MONTH); // current month
    int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
    // date picker dialog
    datePickerDialog = new DatePickerDialog(MainActivity.this,
         new DatePickerDialog.OnDateSetListener() {

                 @Override
                 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                     // set day of month , month and year value in the edit text
                     date.setText(dayOfMonth + "/"+ (monthOfYear + 1) + "/" + year);
                 }
         }, mYear, mMonth, mDay);
                datePickerDialog.show();
    }
});

When you click on the Edittext it will open the Calendar.

Related