Thursday, January 3, 2013

Android-DatePicker

Override onCreateDialog metthod in your activity


@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
datePicker = new DatePickerDialog(this, datePickerListener,
year, month,day);
return datePicker;
                   }
return null;
}

call whereever necessary the date picker by calling 
showDialog(DATE_DIALOG_ID);

after selection of date from datepicker you can get control in to this method:-


private DatePickerDialog.OnDateSetListener datePickerListener 
= new DatePickerDialog.OnDateSetListener() {

// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
               };
};

When you want to call dialog again implement onPrepareDialog method like this:-
When you call again the date picker dialog the control will not go in to oncreatedialog method it comes to onPrepareDialog method. So implement this method if you want to call date picker at different contexts in activity.



@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {

case DATE_DIALOG_ID: ((DatePickerDialog)dialog).show();
}
}




No comments:

Post a Comment