We want to achieve this effect, such:
Click set date and time:
Click settings to bring up the following content:
The last point is to display the date and time in the preceding text box.
Implementation Code:
Package org. crazyit. Dialog;
Import java. util. calendar;
Import Android. App. activity;
Import Android. App. datepickerdialog;
Import Android. App. Dialog;
Import Android. App. timepickerdialog;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Import Android. widget. datepicker;
Import Android. widget. edittext;
Import Android. widget. timepicker;
/**
* @ Author Wu rihui
*/
Public class datedialog extends activity {
// Used to splice the date and time, and finally used to display
Stringbuilder STR = new stringbuilder ("");
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Button datebn = (button) findviewbyid (R. Id. datebn );
// Bind the listener to the "set date" button.
Datebn. setonclicklistener (New onclicklistener (){
@ Override
Public void onclick (View Source ){
Calendar c = calendar. getinstance ();
// Create a datepickerdialog dialog box and display it
Dialog datedialog = new datepickerdialog (datedialog. This,
// Bind the listener
New datepickerdialog. ondatesetlistener (){
@ Override
Public void ondateset (datepicker DP, int year,
Int month, int dayofmonth ){
Str. append (Year + "-" + (month + 1) + "-"
+ Dayofmonth + "");
Calendar time = calendar. getinstance ();
Dialog timedialog = new timepickerdialog (
Datedialog. This,
// Bind the listener
New timepickerdialog. ontimesetlistener (){
@ Override
Public void ontimeset (
Timepicker TP,
Int hourofday, int minute ){
Str. append (hourofday + ":"
+ Minute );
Edittext show = (edittext) findviewbyid (R. Id. Show );
Show. settext (STR );
}
}
// Set the initial time
, Time. Get (calendar. hour_of_day), time
. Get (calendar. Minute)
// True indicates that the 24-hour format is used.
, True );
Timedialog. settitle ("select a date ");
Timedialog. Show ();
}
}
// Set the initial date
, C. Get (calendar. Year), C. Get (calendar. month), c
. Get (calendar. day_of_month ));
Datedialog. settitle ("select a date ");
Datedialog. Show ();
}
});
}
}
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"
Android: gravity = "center_horizontal"
>
<Edittext
Android: Id = "@ + ID/Show"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: editable = "false"
/>
<Button
Android: Id = "@ + ID/datebn"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "set date and time"
/>
</Linearlayout>