Android date dialog box NumberPicker usage tutorial

Source: Internet
Author: User

Android date dialog box NumberPicker usage tutorial
NumberPicker is a control introduced after Android3.0, and NumberPicker is used to select a group of predefined numbers. For example, if the time hour is valid for only 0-23, you can set it through setMinValue and setMaxValue.

When using this control, pay attention to its two listener and one formatter: One listener is used to listen for changes to the current value, and the other listener is used to listen to the scroll status of the control; formatter is used to format and display the value in the control. The following describes these interfaces one by one:

1. NumberPicker. OnValueChangeListener: its function is public void onValueChange (NumberPicker picker, int oldVal, int newVal). The value selected before oldVal is the value currently selected by newValue.

2. NumberPicker. OnScrollListener: it has three internal scroll states: SCROLL_STATE_FLING, SCROLL_STATE_IDLE, and SCROLL_STATE_TOUCH_SCROLL.

SCROLL_STATE_TOUCH_SCROLL: the user presses down and slides.

SCROLL_STATE_FLING: equivalent to the subsequent slide operation of SCROLL_STATE_TOUCH_SCROLL.

SCROLL_STATE_IDLE: NumberPicker does not scroll.

3. NumberPicker. Formatter: format the displayed number. For example, format 0-23 to 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 < 10) {          Str = "0" + Str;          }          return Str;      }  
The value is between 0 and 23, and the number smaller than 10 is preceded by "0 ".

 

After introducing NumberPicker, we need to implement our functions today. First, let's take a look at the following:

Isn't it very beautiful? In this way, we can use it directly if we need this effect in our project in the future. To achieve this effect, we must first look at our layout. In fact, there are three NumberPicker in the layout as follows:

 

 
     
          
           
            
             
       
      
     
    
   
  
 
The three NumberPicker lapicks show our results. After the layout is complete, we need to find these controls and add listeners to them to implement some functions, here, the custom FrameLayout is made in the Direct Fill layout. Let's take a look, as shown below:

 

 

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 Num BerPicker mHourSpinner; private final NumberPicker mMinuteSpinner; private Calendar mDate; private int mHour, mMinute; private String [] hour = new String [7]; private hour; public DateTimePicker (Context context Context) {super (context);/** fetch system time */mDate = Calendar. getInstance (); mHour = mDate. get (Calendar. HOUR_OF_DAY); mMinute = mDate. get (Calendar. MINU TE);/*** load Layout */inflate (context, R. layout. datedialog, this);/*** initialization control */mDateSpinner = (NumberPicker) this. 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 (23); mHourSpinner. setMinValue (0); mHour Spinner. setValue (mHour); mHourSpinner. setOnValueChangedListener (mOnHourChangedListener); mMinuteSpinner = (NumberPicker) this. findViewById (R. id. np_minute); mMinuteSpinner. setMaxValue (59); mMinuteSpinner. setMinValue (0); mMinuteSpinner. setValue (mMinute); mMinuteSpinner. setOnValueChangedListener (mOnMinuteChangedListener);}/***** control listener */private NumberPicker. onValueChangeListener mOnDateChangedListener = n Ew OnValueChangeListener () {@ Overridepublic void onValueChange (NumberPicker picker, int oldVal, int newVal) {mDate. add (Calendar. DAY_OF_MONTH, newVal-oldVal);/***** update date */updateDateControl ();/***** pass the value to the interface */onDateTimeChanged () ;}}; private NumberPicker. onValueChangeListener mOnHourChangedListener = new OnValueChangeListener () {@ Overridepublic void onValueChange (NumberPicker picker, int oldVal, int ne WVal) {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 updatecontrol () {/*** day of the week algorithm */Calendar cal = Calendar. getInstance (); cal. setTimeIn Millis (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. set Value (7/2); mDateSpinner. invalidate ();}/** interface callback parameter is the current View year month day hour minute */public interface O NDateTimeChangedListener {void onDateTimeChanged (DateTimePicker view, int year, int month, int day, int hour, int minute );} /** public Method */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 finds the three controls and gives them setMinValue (), setMaxValue (), that is, the maximum value and the minimum value. After the settings are complete, we add three listening methods under the setOnValueChangedListener listener respectively. In the mOnDateChangedListener method, an updateDateControl () method is added, which is updatecontrol () this method mainly involves the relational algorithm of the month and the day of the week,

After writing this, the value is also obtained, but we need to transfer the value out. Next we define an interface to implement callback. Next let's take a look at the dialog box class, as shown below:

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 impl EmentsOnClickListener {private DateTimePicker mDateTimePicker; private Calendar mDate = Calendar. getInstance (); private OnDateTimeSetListener mOnDateTimeSetListener; @ SuppressWarnings ("deprecation") public listener (Context context, long date) {super (context); mDateTimePicker = new DateTimePicker (Context ); setView (mDateTimePicker);/** implementation interface to implement the Method */mDateTimePicker. setOnDateTimeChangedListene R (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 return * control seconds */public interface OnDateTimeSetListener {void OnDateTimeSet (AlertDialog Diener, 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);}/** make the Activity public */public void setOnDateTimeSetListener (OnDateTimeSetListener callBack) {mOnDateTimeSetListener = callBack ;} public void onClick (DialogInterface arg0, int arg1) {if (mOnDateTimeSetListener! = Null) {mOnDateTimeSetListener. OnDateTimeSet (this, mDate. getTimeInMillis ());}}}

 

Let's look at a row. First, we inherit AlertDialog. Next we are new DateTimePicker. This is the class we just wrote. Our class Object implements the interface we just wrote, although the value is obtained, it is not displayed here. Therefore, we need to define an interface to implement the DateTimePickerDialog object. The following is our written interface, we have written so many lines of code in MainActivity. Let's take a look, as shown below:

 

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 ();/*** implementation 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 String to a time String in 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, we still use the new DateTimePickerDialog class. We pass the system time. In this way, the time dialog box displays the system time. We use this class object to implement the interface we just wrote, in the implementation, we define another method to convert long-time format strings to time yyyy-MM-dd HH: mm: ss, in this way, I use a Toast to pop up the values in the interface. OK, so that we can achieve it. If you do not understand anything, leave a message below.

 

 

 

 


 

 

 

Related Article

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.