Display Date Picker Dialog in Android

Display Date Picker Dialog in Android

A 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 the 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 the 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 android.widget.Button
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)
        val myButton: Button = findViewById(R.id.myButton)
        myButton.setOnClickListener { showDatePicker() }
    }

    private fun showDatePicker()
    {
        val dialog = DatePickerDialog(
            this,
            { _, 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

Cancel reply

Your email address will not be published.