TimePicker Dialog is used in many applications where we have to book appointments based on a specific time. This widget is seen in the applications where we have to select specific time slots. In this article, we will take a look at How to use TimePicker Dialog on Android.
Create/Start a New Project in Android Studio.
- Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail.
- 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:id="@+id/idRLContainer" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--on below line we are creating a text view--> <TextView android:id="@+id/idTVSelectedTime" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/idBtnPickTime" android:layout_centerInParent="true" android:layout_margin="20dp" android:gravity="center" android:padding="10dp" android:text="Time" android:textAlignment="center" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <!--on below line we are creating a button for date picker--> <Button android:id="@+id/idBtnPickTime" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="20dp" android:text="Pick Time" android:textAllCaps="false" /> </RelativeLayout>
Working with the MainActivity file
Kotlin
package com.ppdevelopers.kotlinproject import android.app.TimePickerDialog import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.util.* class MainActivity : AppCompatActivity() { lateinit var pickTimeBtn: Button lateinit var selectedTimeTV: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // on below line we are initializing our variables. pickTimeBtn = findViewById(R.id.idBtnPickTime) selectedTimeTV = findViewById(R.id.idTVSelectedTime) pickTimeBtn.setOnClickListener { // on below line we are getting the instance of our calendar. val c = Calendar.getInstance() // on below line we are getting our hour, minute. val hour = c.get(Calendar.HOUR_OF_DAY) val minute = c.get(Calendar.MINUTE) // on below line we are initializing our Time Picker Dialog val timePickerDialog = TimePickerDialog( this,{ view, hourOfDay, minute -> // on below line we are setting selected time in our text view. selectedTimeTV.setText("$hourOfDay:$minute") },hour,minute,false) // at last we are calling show to // display our time picker dialog. timePickerDialog.show() } } }