Time Picker Dialog in Android

06 Jun, 2021
Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick the valid time for the day in our application. The time picker interface exists basically in two modes one is under XML layout and another is a dialog. In this discussion, it’s been demonstrated how to implement TimePicker Dialog in android. Refer to TimePicker in Kotlin for the TimePicker in the XML layout. Have a look at the following image to get an overview of the discussion.
Steps to implement Time Picker Dialog in Android app
Step 1: Create an empty activity project
Create an empty activity Android Studio project and select Kotlin as the programming language. Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
The main layout of the application contains a button and TextView to preview the picked time. To implement the same layout invoke the following code inside the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     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"    tools:context=".MainActivity"    tools:ignore="HardcodedText">      <Button        android:id="@+id/pick_time_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="128dp"        android:text="PICK TIME"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />      <TextView        android:id="@+id/preview_picked_time_textView"        style="@style/TextAppearance.MaterialComponents.Headline6"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="32dp"        android:text="Preview picked time here"        app:layout_constraintEnd_toEndOf="@+id/pick_time_button"        app:layout_constraintStart_toStartOf="@+id/pick_time_button"        app:layout_constraintTop_toBottomOf="@+id/pick_time_button" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Before Heading to implement the TimePicker dialog, understanding the dialog anatomy is important
Step 3: Working with MainActivity.kt file
In the MainActivity.kt file the instance of TimePickerDialog which takes 5 parameters.
TimePickerDialog(Context, TimePickerDialogListener, DefaultHourOfDialog(Int), DefaultMinuteOfDialog(Int), is24HourView(boolean))
To implement TimePicker Dialog invoke the following code.
Kotlin
import android.app.TimePickerDialogimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport android.widget.TimePicker  class MainActivity : AppCompatActivity() {      lateinit var previewSelectedTimeTextView: TextView      // listener which is triggered when the      // time is picked from the time picker dialog    private val timePickerDialogListener: TimePickerDialog.OnTimeSetListener =        object : TimePickerDialog.OnTimeSetListener {            override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {                  // logic to properly handle                   // the picked timings by user                val formattedTime: String = when {                    hourOfDay == 0 -> {                        if (minute < 10) {                            "${hourOfDay + 12}:0${minute} am"                        } else {                            "${hourOfDay + 12}:${minute} am"                        }                    }                    hourOfDay > 12 -> {                        if (minute < 10) {                            "${hourOfDay - 12}:0${minute} pm"                        } else {                            "${hourOfDay - 12}:${minute} pm"                        }                    }                    hourOfDay == 12 -> {                        if (minute < 10) {                            "${hourOfDay}:0${minute} pm"                        } else {                            "${hourOfDay}:${minute} pm"                        }                    }                    else -> {                        if (minute < 10) {                            "${hourOfDay}:${minute} am"                        } else {                            "${hourOfDay}:${minute} am"                        }                    }                }                  previewSelectedTimeTextView.text = formattedTime            }        }      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // instance of the UI elements        val buttonPickTime: Button = findViewById<Button>(R.id.pick_time_button)        previewSelectedTimeTextView = findViewById<TextView>(R.id.preview_picked_time_textView)          // handle the pick time button to          // open the TimePickerDialog        buttonPickTime.setOnClickListener {            val timePicker: TimePickerDialog = TimePickerDialog(                // pass the Context                this,                // listener to perform task                  // when time is picked                timePickerDialogListener,                // default hour when the time picker                  // dialog is opened                12,                // default minute when the time picker                  // dialog is opened                10,                // 24 hours time picker is                   // false (varies according to the region)                false            )              // then after building the timepicker               // dialog show the dialog to user            timePicker.show()        }    }}
Output:
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android