To create a datepickerdialog:
1. Declare a listener and use an anonymous internal class:
Datepickerdialog. ondatesetlistener = new datepickerdialog.
Ondatesetlistener (){
@ Override
Public void ondateset (datepicker view, int year, int monthofyear,
Int dayofmonth ){
System. Out. println (Year + ":" + monthofyear + ":" + dayofmonth );
}
};
2. Rewrite the protected dialog oncreatedialog (int id) method of the activity class.
@ Override
Protected dialog oncreatedialog (int id ){
Switch (ID ){
Case date_picker_id:
Return new datepickerdialog (this, ondatesetlistener, 2011, 8, 26 );
}
Return NULL;
}
3. Call the showdialog (date_picker_id) method to display the date.
Example:
Main. xml file
<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Textview
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: Id = "@ + ID/textview"
/>
<Button
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: Id = "@ + ID/button"
Android: text = "display date"
/>
</Linearlayout>
Java code:
Import Android. App. activity;
Import Android. App. datepickerdialog;
Import Android. App. Dialog;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;
Import Android. widget. datepicker;
Import Android. widget. textview;
Public class datepickeractivity extends activity {
Private Static final int date_picker_id = 1;
Private button = NULL;
Private textview TV = NULL;
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
TV = (textview) findviewbyid (R. Id. textview );
Button = (button) findviewbyid (R. Id. Button );
Button. setonclicklistener (New View. onclicklistener (){
@ Override
Public void onclick (view v ){
Showdialog (date_picker_id); // This method is used to display datepickerdialog
}
});
}
// Listener, which listens to the set button of datepickerdialog under the user point
Private datepickerdialog. ondatesetlistener = new datepickerdialog. ondatesetlistener (){
@ Override
Public void ondateset (datepicker view, int year, int monthofyear,
Int dayofmonth ){
TV. settext (Year + ":" + monthofyear + ":" + dayofmonth );
}
};
@ Override
Protected dialog oncreatedialog (int id ){
Switch (ID ){
Case date_picker_id:
Return new datepickerdialog (this, ondatesetlistener, 2011, 8, 26 );
}
Return NULL;
}
}
For more details, see Google API