Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Hello, Views >

Hello, DatePicker

A DatePicker is a widget that allows the user to select a month, day and year.

  1. Start a new project/Activity called HelloDatePicker.
  2. Open the layout file and make it like so:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TextView android:id="@+id/dateDisplay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""/>
    
        <Button android:id="@+id/pickDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Change the date"/>
    
    </LinearLayout>
    

    For the layout, we're using a vertical LinearLayout, with a TextView that will display the date and a Button that will initiate the DatePicker dialog. With this layout, the TextView will sit above the Button. The text value in the TextView is set empty, as it will be filled with the current date when our Activity runs.

  3. Open HelloDatePicker.java. Insert the following to the HelloDatePicker class:
        private TextView mDateDisplay;
        private Button mPickDate;
    
        private int mYear;
        private int mMonth;
        private int mDay;
    
        static final int DATE_DIALOG_ID = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            // capture our View elements
            mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            mPickDate = (Button) findViewById(R.id.pickDate);
    
            // add a click listener to the button
            mPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });
    
            // get the current date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
    
            // display the current date
            updateDisplay();
        }
    

    Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.

    We start by instantiating variables for our Views and date fields. The DATE_DIALOG_ID is a static integer that uniquely identifies the Dialog. In the onCreate() method, we get prepared by setting the layout and capturing the View elements. Then we create an on-click listener for the Button, so that when it is clicked it will show our DatePicker dialog. The showDialog() method will pop-up the date picker dialog by calling the onCreateDialog() callback method (which we'll define in the next section). We then create an instance of Calendar and get the current year, month and day. Finally, we call updateDisplay()—our own method (defined later) that will fill the TextView.

  4. After the onCreate() method, add the onCreateDialog() callback method (which is called by showDialog())
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
    

    This method is passed the identifier we gave showDialog() and initializes the DatePicker to the date we retrieved from our Calendar instance.

  5. Following that, add the updateDisplay() method:
        // updates the date we display in the TextView
        private void updateDisplay() {
            mDateDisplay.setText(
                new StringBuilder()
                        // Month is 0 based so add 1
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
        }
    

    This uses the member date values to write the date to our TextView.

  6. Finally, add a listener that will be called when the user sets a new date:
        // the callback received when the user "sets" the date in the dialog
        private DatePickerDialog.OnDateSetListener mDateSetListener =
                new DatePickerDialog.OnDateSetListener() {
    
                    public void onDateSet(DatePicker view, int year, 
                                          int monthOfYear, int dayOfMonth) {
                        mYear = year;
                        mMonth = monthOfYear;
                        mDay = dayOfMonth;
                        updateDisplay();
                    }
                };
    

    This OnDateSetListener method listens for when the user is done setting the date (clicks the "Set" button). At that time, this fires and we update our member fields with the new date defined by the user and update our TextView by calling updateDisplay().

  7. Now run it.

When you press the "Change the date" button, you should see the following:

References

← Back to Hello, Views


 
 
  Published under the terms fo the Apache 2.0 License Design by Interspire