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.
Use the DatePicker
http://developer.android.com/reference/android/widget/DatePicker.html
It is availible since API Level 1
Here a example how to use the DatePickerDialog.
First add a TextView and a Button to your layout.xml
<Button android:id="@+id/myDatePickerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Date"/>
<TextView android:id="@+id/showMyDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Next you have to initialize the Button and TextView in the onCreate Method of your layout. You need this class variables
private int mYear;
private int mMonth;
private int mDay;
private TextView mDateDisplay;
private Button mPickDate;
static final int DATE_DIALOG_ID = 0;
Here the onCreate method
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDateDisplay = (TextView) findViewById(R.id.showMyDate);
mPickDate = (Button) findViewById(R.id.myDatePickerButton);
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDisplay();
}
UpdateDisplay method:
private void updateDisplay() {
this.mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
The callback listener for the DatePickDialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
The onCreateDialog method, called by showDialog()
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
Hope it helps, used it and it works fine.
Example from
http://developer.android.com/guide/tutorials/views/hello-datepicker.html