Android Date Picker Example

Applicable To: As specified
Updated: Wed 15 Jun, 2016 GMT

In this project we will open a Date Picker Dialogue on a button click, set the Date and show the newly set Date in a simple Text View and optionally support API >=8.

Preview

Objectives:

  1. Open a Date Picker Dialogue on a button click.
  2. Set the Date and show the newly set Date in a simple Text View.
  3. Support API >=8 (optional).

Mechanism:

I am going to use DialogFragment (api >=11) to host the Date Picker. DialogFragment manages the life cycle and allows different layout configurations for the DatePicker.

To show a Date picker dialog, we need to define a fragment class (DatePickerFragment) which extends the DialogFragment class and returns a DatePickerDialog from its onCreateDialog() method.

Let's start the project:

Java Part:

First create an empty project in Android Studio with a blank Activity. Then create a new Fragment class named DatePickerFragment, and let it extend DialogFragment and implement DatePickerDialog.OnDateSetListener.

To be specific, copy paste the following codes in your DatePickerFragment class:

package com.neurobin.aapps.datepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

/**
 * Created by jahid on 12/10/15.
 */
public class DatePickerFragment extends DialogFragment
         implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        TextView tv1= (TextView) getActivity().findViewById(R.id.textview1);
        tv1.setText("Year: "+view.getYear()+" Month: "+view.getMonth()+" Day: "+view.getDayOfMonth());

    }
}

The method onDateSet() is where you get the Date set by user. Here, I am taking the Year, Month, Day and displaying them with the TextView in the MainActivity.

Now, Make your MainActivity class look like this:

package com.neurobin.aapps.datepicker;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

}

The last method in this class is the one which is responsible for showing the DatePickerDialog.

XML Part:

The XML part is simple, just a TextView and a Button:

activity_main.xml:

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:text="@string/init_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pick_date"
        android:onClick="showDatePickerDialog"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

strings.xml:

<resources>
    <string name="app_name">DatePicker</string>

    <string name="action_settings">Settings</string>
    <string name="pick_date">Pick Date</string>
    <string name="init_text">Neurobin Date Picker Example</string>
</resources>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.neurobin.aapps.datepicker" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

That's it. Run and see the outcome.

Without making all these changes yourself you can just download the whole project and import it to Android Studio (Links at top).