TimePickerDialog — Android Studio Tutorial | Time Picker Using Kotlin in Android Studio

Devendra Chavan
2 min readAug 11, 2023

--

Hello, and Welcome to the #CodingWithDev​ channel!

In this tutorial, you will learn how to create a Time Picker in an Android app using Kotlin.
The tutorial covers the following key points:
• Implementing Time Picker: You will learn how to add a Time Picker widget to your app’s layout XML file and how to reference it in your Kotlin code.
• Showing the Time Picker dialog: The tutorial will show you how to display a Time Picker dialog when a button is clicked. The dialog will allow the user to pick a Time from a time picker dialog.

Video

Step 1: Create a new project OR Open your project

Step 2: activity_main.xml layout file code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">

<Button
android:id="@+id/pickTimeBtn"
android:text="Pick Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/timeTv"
android:text="Time"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


</LinearLayout>

Step 3: MainActivity.kt Activity code

import android.app.TimePickerDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

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

val mPickTimeBtn = findViewById<Button>(R.id.pickTimeBtn)
val textView = findViewById<TextView>(R.id.timeTv)

mPickTimeBtn.setOnClickListener {
val cal = Calendar.getInstance()
val timeSetListener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
cal.set(Calendar.HOUR_OF_DAY, hour)
cal.set(Calendar.MINUTE, minute)
textView.text = SimpleDateFormat("HH:mm").format(cal.time)
}
TimePickerDialog(this, timeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), true).show()
}


}
}

Step 4: Output

--

--

Devendra Chavan
Devendra Chavan

Written by Devendra Chavan

Android Mobile Application Developer

No responses yet