Android 0 Basics Section 57th: Date picker DatePicker and time picker Timepicker

Source: Internet
Author: User



In the actual development, often meet some time selector, date selector, digital selector and other requirements, then from the beginning of this period to learn about Android Common selectors, today is learning DatePicker and timepicker.











First, DatePicker





DatePicker is a relatively simple component, derived from Framelayout, for the user to select a date. It provides some methods based on framelayout to get the date selected by the current user, and if the program needs to get the date selected by the user, it can be implemented by listening for DatePicker add Ondatechangedlistener.



Common XML attributes that use DatePicker are as follows:


    • Android:calendarviewshown: Sets the date to select whether to display the CalendarView component.

    • Android:endyear: Sets the date selector to allow selection of the last year.

    • Android:maxdate: Sets the maximum date for the date selector. Specifies the maximum date in mm/dd/yyyy format.

    • Android:mindate: Sets the minimum date for the date selector. Specifies the minimum date in mm/dd/yyyy format.

    • Android:spinnersshown: Sets whether the date selector displays the spinner Date selection component.

    • Android:startyear: Sets the date selector to allow the first year of selection.



Next, a simple example program is used to learn the use of DatePicker.



Continue to use the Advancedviewsample module of the Widgetsample project to create a datepicker_layout.xml file in the app/main/res/layout/directory populated with the following code snippet:


 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:startYear="2015"
        android:endYear="2020"
        android:calendarViewShown="true"
        android:spinnersShown="true" />
</RelativeLayout>


Create a new Datepickeractivity.java file, load the new layout file above, initialize the DatePicker and get the user's choice, with the following code:


package com.jinyu.cqkxzsxy.android.advancedviewsample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

/ **
 * @Creator 鑫 鱻
 * @Description Android zero-based entry to the proficient tutorial series, welcome to follow the public account ShareExpert
 * /
public class DatePickerActivity extends AppCompatActivity {
    private DatePicker mDatePicker = null; // date picker
    private Calendar mCalendar = null; // calendar
    private int mYear; // year
    private int mMonth; // month
    private int mDay; // day

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.datepicker_layout);

        // Get the calendar object
        mCalendar = Calendar.getInstance ();
        // Get the current year, month, and day information
        mYear = mCalendar.get (Calendar.YEAR);
        mMonth = mCalendar.get (Calendar.MONTH);
        mDay = mCalendar.get (Calendar.DAY_OF_MONTH);

        // Get DatePicker component
        mDatePicker = (DatePicker) findViewById (R.id.datePicker);
        // DatePicker initialization
        mDatePicker.init (mYear, mMonth, mDay, new DatePicker.OnDateChangedListener () {
            @Override
            public void onDateChanged (DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Toast.makeText (DatePickerActivity.this,
                        year + "year" + (monthOfYear + 1) + "month" + dayOfMonth + "day",
                        Toast.LENGTH_SHORT) .show ();
            }
        });
    }
} 


The above program code is the code that DatePicker binds the event listener, and the listener is triggered when the user chooses the date through this component.



Running the program, you can see the interface effect shown.











Second, Timepicker





Timepicker and DatePicker are very similar, mainly for the user to choose the time. Also on the basis of Framelayout provides a number of methods to obtain the current user selected time, if the program needs to get the user's choice of time can be achieved by adding ontimechangedlistener for Timepicker to listen.



Next, a simple example program is used to learn the use of Timepicker.



Continue to use the Advancedviewsample module of the Widgetsample project to create a timepicker_layout.xml file in the app/main/res/layout/directory populated with the following code snippet:


 
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
</RelativeLayout>


Create a new Timepickeractivity.java file, load the new layout file above, initialize the Timepicker and get the user's choice, with the following code:


package com.jinyu.cqkxzsxy.android.advancedviewsample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

/ **
 * @Creator 鑫 鱻
 * @Description Android zero-based entry to the proficient tutorial series, welcome to follow the public account ShareExpert
 * /
public class TimePickerActivity extends AppCompatActivity {
    private TimePicker mTimePicker = null; // time picker
    private Calendar mCalendar = null; // calendar
    private int mHour; // hour
    private int mMinute; // min

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.timepicker_layout);

        // Get the calendar object
        mCalendar = Calendar.getInstance ();
        // Get the corresponding hour and minute information
        mHour = mCalendar.get (Calendar.HOUR_OF_DAY);
        mMinute = mCalendar.get (Calendar.MINUTE);

        // Get TimePicker component
        mTimePicker = (TimePicker) findViewById (R.id.timePicker);
        // Specify a listener for TimePicker
        mTimePicker.setOnTimeChangedListener (new TimePicker.OnTimeChangedListener () {
            @Override
            public void onTimeChanged (TimePicker view, int hourOfDay, int minute) {
                Toast.makeText (TimePickerActivity.this, hourOfDay + ":" + minute,
                        Toast.LENGTH_SHORT) .show ();
            }
        });
    }
} 


The above program code is the code that Timepicker binds the event listener, and the listener is triggered when the user chooses the time through this component.



Running the program, you can see the interface effect shown.






At this point, the simple use of DatePicker and Timepicker first, more multi-functional advice to explore more practice.






Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!



This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if necessary reprint please contact the author authorized, hereby declare!






Past period Summary share:



Android 0 Basics Introduction 1th: Android's past life



Android 0 Basics Section 2nd: Android system Architecture and application components those things



Android 0 Basics Section 3rd: Bring you up to talk about Android development environment



Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick



Android 0 Basics 5th: Use ADT bundles to easily meet the goddess



Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess



Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey



Android 0 Basics 8th: HelloWorld, the starting point for my first trip



Android 0 Basics 9th: Android app, no code can be developed



Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio



Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project



Android 0 Basics 12th: Get familiar with the Android studio interface and start selling



Android 0 Basics 13th: Android Studio Configuration optimization to create a development tool



Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era



Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing



Android 0 Basics Section 16th: Android User Interface Development overview



Android 0 Basics Section 17th: text box TextView



Android 0 Basics Section 18th: Input box EditText



Android 0 Basics Get started section 19th: Buttons button



Android 0 Basics 20th: check box checkbox and radio button radiobutton



Android 0 Basics Section 21st: Switch Components ToggleButton and switch



Android 0 Basics Section 22nd: Image View ImageView



Android 0 Basics Section 23rd: Image button ImageButton and zoom button Zoombutton



Android 0 Basics Section 24th: Customize view simple to use to create your own controls



Android 0 Basics Section 25th: Simple and most commonly used linearlayout linear layouts



Android 0 Basics Section 26th: Two alignments, layout_gravity and gravity differ greatly



Android 0 Basics section 27th: Using padding and margin correctly



Android 0 Basics Section 28th: Easy to master relativelayout relative layout



Android 0 Basics 29th: Use tablelayout table layouts



Android 0 Basics 30th: Two minutes master Framelayout frame layout



Android 0 Basics Section 31st: absolutelayout absolute Layout with less



Android 0 Basics Section 32nd: New GridLayout Grid layout



Android 0 Basics section 33rd: Android Event Handling overview



Android 0 Basics Section 34th: Listening-based event handling in Android



Android 0 Basics Section 35th: Callback-based event handling in Android



Android 0 Basics Section 36th: Handling of Android system events



Android 0 Basics 37th: First Knowledge ListView



Android 0 Basics 38th: First Knowledge Adapter



Android 0 Basics section 39th: listactivity and custom list items



Android 0 Basics Section 40th: Customizing Arrayadapter



Android 0 Basics Section 41st: Using Simpleadapter



Android 0 Basics Section 42nd: Customizing Baseadapter



Android 0 Basics section 43rd: ListView Optimization and List End-to-end use



Android 0 Basics Section 44th: ListView Data Dynamic Update



Android 0 Basic Getting Started section 45th: Grid view GridView



Android 0 Basics section 46th: List Options Box spinner



Android 0 Basic Getting Started section 47th: AutoComplete text Box Autocompletetextview



Android 0 Basics Section 48th: Collapsible list Expandablelistview



Android 0 Basics section 49th: Adapterviewflipper picture Carousel



Android 0 Basics Section 50th: StackView card Stacking



Android 0 Basics Section 51st: progress bar ProgressBar



Android 0 Basics section 52nd: Customizing ProgressBar Cool progress bar



Android 0 Basics 53rd: Drag bar Seekbar and star rating bar Ratingbar



Android 0 Basics section 54th: View switch Components Viewswitcher



Android 0 Basics Section 55th: Imageswitcher and Textswitcher



Android 0 Basics Section 56th: Flip View Viewflipper









Android 0 Basics Section 57th: Date picker DatePicker and time picker Timepicker


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.