Android DatePicker Example

Android DatePicker is a facility that allow you to give option to select date in your android application. The date will be consisting of year, month and day. Android itself is providing a DatePickerDialog class for selecting date. In this tutorial we will see how to implement DatePicker in android.This Android DatePicker example will consist of a TextView and a Button, the onclick of button will open a date picker and the selected date will be displayed in the TextView.

  1. First step is to add the following code to your layout file, which will create a Textview and a Button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.picker.MainActivity"
tools:showIn="@layout/activity_main">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true">

<TextView
android:id="@+id/tv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"/>

<Button
android:id="@+id/btn_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:textColor="@color/white"
android:layout_marginTop="5dp"
android:text="Set Date"/>

</LinearLayout>

</RelativeLayout>

2. Now use the following code in the onclick of button in your activity.

// Get Current Date
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);


DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
        new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {

                tv_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

            }
        }, year, month, day);
datePickerDialog.show();

Now run the code, here is the expected output.

android-date-picker
android-date-picker

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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