Date Picker Widget

When you want the user to set a date, you need a date picker. To do this, a DatePicker class is used for this task.

The DatePicker displays a calendar-like view that enables the user to choose the needed date. It is a widget for selecting a date. The date can be selected by a year, month, and day spinners or a CalendarView. The set of spinners and the calendar view are automatically synchronized. The client can customize whether only the spinners, or only the calendar view, or both to be displayed. Also the minimal and maximal date from which dates to be selected can be customized.

Below are the steps to create the DatePicker sample program.

Step 1.

Create a new project named HelloDatePicker. The project structure will look like this:

Step 2.

Open the generated xml layout file and add the following contents.

Step 3.

Modify the Java code. Override the method onCreate with the following code:

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

displayCurrentDateOnView();

addListenerOnButton();

This program contains additional methods that include displayCurrentDateOnView(), addListenerOnButton(), onCreateDialog() and DatePickerDialog.OnDatesetListener(). We use the method displayCurrentDateOnView to display the current date. This method initializes the objects we have declared in our layout and the variables that we will be using in our program. We also have the method addListenerOnButton() to handle clicks on the button we provided in our view. The methods onCreateDialog() and DatePickerDialog.OnDateSetListener() are dialog object related methods.

Make sure that you import the following packages/classes:

import java.util.Calendar;

import android.app.Activity;

import android.app.DatePickerDialog;

import android.app.Dialog;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.DatePicker;

import android.widget.TextView;

Step 4.

Run the program.

Note: I am using the ADT build v22.0.4-741630.

Leave a Reply

Your email address will not be published. Required fields are marked *