The use of Android Date dialog box Numberpicker tutorial

Source: Internet
Author: User

Numberpicker is a control introduced after Android3.0,Numberpicker is a control that selects a set of predefined numbers. For example, the choice of time hour is only 0-23 valid, can be set by Setminvalue and Setmaxvalue.

When using this control, be aware of his two listener and a formatter: a listener is used to listen for changes to the current value, and a listener to listen for the scroll state of the control ; Formatter is used to format the display of value in the control. Here are a few of these interfaces:

1,Numberpicker.onvaluechangelistener : its function public void Onvaluechange (Numberpicker picker, int oldval, int newval); oldval the previous selected value, NewValue the currently selected value.

2,numberpicker.onscrolllistener: There are three kinds of SCROLL state scroll_state_fling, Scroll_state_idle, Scroll_ in its interior State_touch_scroll.

Scroll_state_touch_scroll: The user presses down and then slides.

Scroll_state_fling: Equivalent to the subsequent slide operation of the Scroll_state_touch_scroll.

Scroll_state_idle:numberpicker is not scrolling.

3,numberpicker.formatter: Formatted display number, for example 0-23 formatted as 00-23. The specific format is defined in the Format function, as follows:

Public String Format (int value) {          String Str = string.valueof (value);          if (value <) {          str = "0" + str;          }          return Str;      }  
The value values are between 0-23 and the number less than 10 is preceded by "0".

After the introduction of Numberpicker, it is necessary to achieve our functions today, first look first, as follows:


is not very beautiful that, so in future we need this effect in the project, it can be used directly. To achieve this effect of course, we must first look at the layout, in fact, the layout of the three Numberpicker as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:gravity=" center "Andro id:orientation= "vertical" > <linearlayout android:layout_width= "wrap_content" android:layout_height = "Wrap_content" android:gravity= "center_horizontal" android:orientation= "Horizontal" Android:paddingL            eft= "3.0dip" > <numberpicker android:id= "@+id/np_date" android:layout_width= "120.0dip"            android:layout_height= "Wrap_content" android:button= "@null"/> <numberpicker            Android:id= "@+id/np_hour" android:layout_width= "50.0dip" android:layout_height= "Wrap_content"            android:layout_marginleft= "5.0dip"/> <textview android:layout_width= "Wrap_content" Android:layout_height= "Wrap_contENT "android:layout_gravity=" center "android:text=": "android:textsize=" 20.0sp "/> <numberpicker android:id= "@+id/np_minute" android:layout_width= "50.0dip" android:l ayout_height= "Wrap_content"/> </LinearLayout></LinearLayout>
This is the three numberpicker layout we just have the effect, the layout is done we will find these controls, and give them to listen, to implement some functions, which are custom framelayout in the direct fill layout. Let's take a look as follows:

Package Com.zqy.datetimepicker.datedialog;import Java.util.calendar;import Com.zqy.datetimepicker.r;import Android.content.context;import Android.text.format.dateformat;import Android.widget.framelayout;import Android.widget.numberpicker;import Android.widget.numberpicker.onvaluechangelistener;public class DateTimePicker Extends Framelayout {Private final numberpicker mdatespinner;private final numberpicker mhourspinner;private final Numberpicker mminutespinner;private Calendar mdate;private int mhour, mminute;private string[] mdatedisplayvalues = new S TRING[7];p rivate ondatetimechangedlistener mondatetimechangedlistener;public DateTimePicker (context context) {Super */* * for system time */mdate = Calendar.getinstance (); mhour = Mdate.get (calendar.hour_of_day); mminute = Mdate.get ( Calendar.minute);/** * Load Layout */inflate (context, r.layout.datedialog, this);/** * Initialize control */mdatespinner = (numberpicker) thi S.findviewbyid (r.id.np_date); mdatespinner.setminvalue (0); Mdatespinner.setmaxvalue (6); updatEdatecontrol (); Mdatespinner.setonvaluechangedlistener (mondatechangedlistener); Mhourspinner = (NumberPicker) This.findviewbyid (r.id.np_hour); mhourspinner.setmaxvalue; mhourspinner.setminvalue (0); MHourSpinner.setValue (Mhour); Mhourspinner.setonvaluechangedlistener (monhourchangedlistener); Mminutespinner = (NumberPicker) This.findviewbyid (R.id.np_minute); Mminutespinner.setmaxvalue (); mminutespinner.setminvalue (0); Mminutespinner.setvalue (Mminute); Mminutespinner.setonvaluechangedlistener (Monminutechangedlistener);} /** * * Control listener */private Numberpicker.onvaluechangelistener Mondatechangedlistener = new Onvaluechangelistener () {@Overri depublic void Onvaluechange (numberpicker picker, int oldval, int newval) {mdate.add (Calendar.day_of_month, Newval-oldva l);/** * Update Date */updatedatecontrol ();/** * Send value to interface */ondatetimechanged ();}}; Private Numberpicker.onvaluechangelistener Monhourchangedlistener = new Onvaluechangelistener () {@Overridepublic void Onvaluechange (numberpicker picker, int oldval, int newval) {mhour = Mhourspinner.getvalue (); ondatetimechanged ();}}; Private Numberpicker.onvaluechangelistener Monminutechangedlistener = new Onvaluechangelistener () {@Overridepublic void Onvaluechange (Numberpicker picker, int oldval, int newval) {Mminute = Mminutespinner.getvalue (); Ondatetimechanged ( );}}; private void Updatedatecontrol () {/** * week algorithm */calendar cal = Calendar.getinstance (); Cal.settimeinmillis ( Mdate.gettimeinmillis ()); Cal.add (Calendar.day_of_year, -7/2-1); mdatespinner.setdisplayedvalues (null); for (int i = 0 ; I < 7; ++i) {Cal.add (calendar.day_of_year, 1); Mdatedisplayvalues[i] = (String) dateformat.format ("Mm.dd eeee", Cal);} Mdatespinner.setdisplayedvalues (mdatedisplayvalues); Mdatespinner.setvalue (7/2); Mdatespinner.invalidate ();} /* The interface callback parameter is the current view month day hour minute */public interface Ondatetimechangedlistener {void ondatetimechanged (DateTimePicker view, int year, Int. Month,int Day, int hour, int minute);} /* * External public methods */public void Setondatetimechangedlistener (OndatetimechangeDlistener callback) {Mondatetimechangedlistener = callback;} private void ondatetimechanged () {if (Mondatetimechangedlistener! = null) { Mondatetimechangedlistener.ondatetimechanged (This,mdate.get (calendar.year), Mdate.get (Calendar.MONTH), MDate.get (Calendar.day_of_month), Mhour, Mminute);}}}
This code is to find the three controls, give them Setminvalue (), Setmaxvalue (), that is, the maximum and minimum values, after the setup is complete, We give them three separate listening setonvaluechangedlistener there are three listening methods, in Mondatechangedlistener This method has a Updatedatecontrol () method, The Updatedatecontrol () method is primarily a relational algorithm for the month and day of the week,

After writing these, the values are also taken, but we need to get the values out, and then we define an interface to implement the callback. Let's take a look at the dialog box class as follows:

Package Com.zqy.datetimepicker.datedialog;import Java.util.calendar;import Com.zqy.datetimepicker.datedialog.datetimepicker.ondatetimechangedlistener;import Android.app.AlertDialog; Import Android.content.context;import Android.content.dialoginterface;import Android.content.dialoginterface.onclicklistener;import Android.text.format.dateutils;public Class Datetimepickerdialog extends Alertdialog implementsonclicklistener {private DateTimePicker mdatetimepicker;private Calendar mdate = calendar.getinstance ();p rivate ondatetimesetlistener Mondatetimesetlistener; @SuppressWarnings (" Deprecation ") Public datetimepickerdialog (context context, long date) {super (context); mdatetimepicker = new DateTimePicker (context); Setview (mdatetimepicker);/* Implements the interface to implement the method inside */mdatetimepicker.setondatetimechangedlistener (New Ondatetimechangedlistener () {@Overridepublic void ondatetimechanged (DateTimePicker view,int Year, int month, int day, int hour, int. minute) {Mdate.set (calendar.year, year); Mdate.set (Calendar.moNTH, month); Mdate.set (Calendar.day_of_month, day); Mdate.set (Calendar.hour_of_day, HOUR); Mdate.set (Calendar.minute , minute); Mdate.set (Calendar.second, 0);/** * Update Date */updatetitle (Mdate.gettimeinmillis ());}); Setbutton ("Set", this); SetButton2 ("Cancel", (Onclicklistener) null); Mdate.settimeinmillis (date); Updatetitle ( Mdate.gettimeinmillis ());} /* Interface Callback * control number of seconds */public interface Ondatetimesetlistener {void Ondatetimeset (Alertdialog dialog, long Date);} /** * Update dialog box date * @param date */private void Updatetitle (long date) {int flag = Dateutils.format_show_year | dateutils.format_show_date| Dateutils.format_show_weekday | Dateutils.format_show_time;settitle (Dateutils.formatdatetime (This.getcontext (), date, flag)); /* * External disclosure Method let activity implement */public void Setondatetimesetlistener (Ondatetimesetlistener callBack) {Mondatetimesetlistener = CallBack;} public void OnClick (dialoginterface arg0, int arg1) {if (Mondatetimesetlistener! = null) { Mondatetimesetlistener.ondatetimeset (this, Mdate.gettimeinmillis ());}}}

We look at the line, first we are inheriting Alertdialog, in the following we are new DateTimePicker, this is the class we just wrote, our class object implementation of the interface we just wrote, the value of the inside to take, although taken, but we are not shown here, So we also need to define the interface, let the Datetimepickerdialog object to implement, the following is our write interface, we wrote so much, just for mainactivity inside a few lines of code, let's see, as follows:

Package Com.zqy.datetimepicker.activity;import Java.text.simpledateformat;import Com.zqy.datetimepicker.r;import Com.zqy.datetimepicker.datedialog.datetimepickerdialog;import Com.zqy.datetimepicker.datedialog.datetimepickerdialog.ondatetimesetlistener;import Android.app.Activity;import Android.app.alertdialog;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public Class Mainactivity extends Activity {private Button btn; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.main); btn = (Button) This.findviewbyid (R.id.button1); Btn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {showDialog ();}});} public void ShowDialog () {datetimepickerdialog dialog = new Datetimepickerdialog (This,system.currenttimemillis ());/** * Implement Interface */dialog.setondatetimesetlistener (new Ondatetimesetlistener () {public void OnDAtetimeset (Alertdialog dialog, long date) {Toast.maketext (Mainactivity.this, "The date you entered is:" + getstringdate (date), Toast.length_long). Show ();}}); Dialog.show ();} /** * Converts a long-time format string to a time yyyy-mm-dd HH:mm:ss * */public static string getstringdate (long date) {SimpleDateFormat formatter = New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String datestring = Formatter.format (date); return datestring;}}
first of all we are new datetimepickerdialog this class, we put the system time passed, so the time dialog box shows the system time, we use this class of objects to implement the interface we just wrote, implement the method inside, we define a Convert a long-time format string to a method of time Yyyy-mm-dd HH:mm:ss, so I use a toast to bounce the value out of the interface. OK, so that we achieve the completion, what do not understand can leave a message below.


SOURCE download, please click here







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.