Display Time Picker Dialog in Android

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

A layout XML file contains a Button that displays a time 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 TimePickerDialog is a simple dialog that contains TimePicker widget that allows to select a time. The TimePickerDialog has OnTimeSetListener that is used to inform when time was selected. The method show() displays a time picker dialog.

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

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

package com.example.app

import android.app.TimePickerDialog
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("HH:mm", Locale.US)
    private val calendar = Calendar.getInstance()
    private val is24HourView = true

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

    private fun showTimePicker()
    {
        val dialog = TimePickerDialog(
            this,
            TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hour)
                calendar.set(Calendar.MINUTE, minute)
                val time = formatter.format(calendar.time)

                Log.d("MY_APP", time)
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            is24HourView
        )

        dialog.show()
    }
}

Leave a Comment

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