Display Date Picker Dialog in Android

date picker dialog is a popup window that allows to select a date. For this functionality Android provides the DatePickerDialog class.

A layout XML file contains a Button that displays a date picker dialog when it was pressed.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Open" />

</RelativeLayout>

The DatePickerDialog is a simple dialog that contains DatePicker widget that allows to select a date. The DatePickerDialog has OnDateSetListener that is used to inform when date was selected. The method show() displays a date picker dialog.

We can use Calendar object to store the selected date and SimpleDateFormat to format a date.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity()
{
    private val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.US)
    private val calendar = Calendar.getInstance()

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myButton.setOnClickListener { showDatePicker() }
    }

    private fun showDatePicker()
    {
        val dialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { _, year, month, day ->
                calendar.set(year, month, day)
                val date = formatter.format(calendar.time)

                Log.d("MY_APP", date)
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )

        dialog.show()
    }
}

Leave a Comment

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