Recipe 2.9 Using the DatePicker

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
UsingDatePicker.zip

Another view that is similar to the TimePicker is the DatePicker. Using the DatePicker, you can enable users to select a particular date on the activity. This recipe shows you how to use the DatePicker.

Solution

Assume you have the following code snippet in your activity_main.xml file, which contains a Button and a DatePicker view:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btnSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:onClick="btnClick"
        android:text="I am all set!" />

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/btnSet" />

</RelativeLayout>

The following code snippet shows the date selected by the user:

package net.learn2develop.usingdatepicker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
    DatePicker datePicker; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.