Android Date Picker example

In this example, there will be an EditText which will be clicked and the Android DatePickerDialog will popup, the user pick a date from the date picker, and the date will show up on the EditText. The EditText will not be focusable.

The EditText in a layout file

<EditText
    android:id="@+id/et_date"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:clickable="true"
    android:focusable="false"
    android:hint="Date"/>

The code for the data picker.

//some of the needed imports
import android.widget.DatePicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;


//private field variables in the Activity class
private Calendar myCalendar = Calendar.getInstance();
private EditText etDate;


//onCreate method of the Activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

	etDate = (EditText) findViewById(R.id.et_date);
	etDate.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View view) {
	        new DatePickerDialog(TheClassName.this, datePickerListener, myCalendar
	                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
	                myCalendar.get(Calendar.DAY_OF_MONTH)).show();        
	    }
	});

	DatePickerDialog.OnDateSetListener datePickerListener = 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);

	        String myFormat = "MM/dd/yy";
	        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
	        etDate.setText(sdf.format(myCalendar.getTime()));
	    }

	};
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search