Display Time Picker Dialog in Android

Display Time Picker Dialog in Android

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

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

Cancel reply

Your email address will not be published.