1.xml Layout file
1 <?XML version= "1.0" encoding= "Utf-8"?>2 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 android:orientation= "vertical" >6 7 <Timepicker8 Android:id= "@+id/timepicker1"9 Android:layout_width= "Match_parent"Ten Android:layout_height= "Wrap_content" /> One A <DatePicker - Android:id= "@+id/datepicker1" - Android:layout_width= "Match_parent" the Android:layout_height= "Wrap_content" /> - - </LinearLayout>
2.java Code
1 Public classMainactivityextendsactionbaractivity {2 3 PrivateDatePicker DP1;4 PrivateTimepicker TP1;5 Private intYear ;6 Private intmonth;7 Private intDay ;8 Private inthour;9 Private intminute;Ten PrivateCalendar cal; One A @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); the Setcontentview (r.layout.main); - //get an object for a calendar -Cal=calendar.getinstance (); - //get information about the day and seconds of the month +Year =Cal.get (calendar.year); -month = Cal.get (calendar.month) +1; +Day =Cal.get (calendar.day_of_month); Ahour =Cal.get (calendar.hour_of_day); atminute =Cal.get (calendar.minute); - -Settitle (year+ "-" +month+ "-" +day+ "" +hour+ ":" +minute); - - //Initialize -DP1 =(DatePicker) Findviewbyid (r.id.datepicker1); inTP1 =(Timepicker) Findviewbyid (r.id.timepicker1); - to //DP1 Initialization + //the realization of DatePicker -Dp1.init (year, Cal.get (Calendar.month), Day,NewOndatechangedlistener () { the * @Override $ Public voidOndatechanged (DatePicker view,intYearintMonthofyear,Panax Notoginseng intdayofmonth) { - theSettitle (year+ "-" + (monthofyear+1) + "-" +dayofmonth); + } A }); the + //the realization of Timepicker -Tp1.setontimechangedlistener (NewOntimechangedlistener () { $ $ @Override - Public voidOntimechanged (Timepicker view,intHourofday,intminute) { - theSettitle (hourofday+ ":" +minute); - }Wuyi }); the - //the realization of Datepickerdialog WuDatepickerdialog DPD =NewDatepickerdialog ( This,NewOndatesetlistener () { - About @Override $ Public voidOndateset (DatePicker view,intYearintMonthofyear, - intdayofmonth) { - -Settitle (year+ "-" + (monthofyear+1) + "-" +dayofmonth); A } + }, year, Cal.get (Calendar.month), Cal.get (Calendar.day_of_month)); the dpd.show (); - $ //the realization of Timepickerdialog theTimepickerdialog TPD =NewTimepickerdialog ( This,NewOntimesetlistener () { the the @Override the Public voidOntimeset (Timepicker view,intHourofday,intminute) { - inSettitle (hourofday+ ":" +minute); the } the}, hour, minute,true); About tpd.show (); the } the}
3. For month, 0 for 1, so use object cal directly to get month information
Android Learning Notes controls DatePicker and Timepicker