Open In App

Time Picker Dialog in Android

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 version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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.




import android.app.TimePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import 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:


Article Tags :