Create TimePicker in Kotlin Programmatically

In this short Kotlin tutorial I am going to share with you how to create a TimePicker in Kotlin programmatically and how to update text label when the value of Hours or Minutes has changed. The below code example will cover:

  • Create TimePicker and add it to LinearLayout
  • Get input from TimePicker when user changes the value of Hours or Minutes
  • Example of using the setOnTimeChangedListener

TimePicker XML Layout File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


TimePicker Example in Kotlin

In the Kotlin code example below we will create a new TimePicker programmatically and we will add it to a LinearLayout. We will then use the setOnTimeChangedListener to listen for events when user changes the value of TimePicker. And when the value is changed, we will read the value of Hour and Minutes and will set them into the textView for display.

package com.appsdeveloperblog.kotlinexample3

import android.os.Build
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.TimePicker

class TimePickerExample : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        val linearLayout = findViewById( as LinearLayout

        val textView = TextView(this)

        val timePicker = TimePicker(this)

        textView.text = "Hour: "+timePicker.hour+ " Minute: "+ timePicker.minute
        timePicker.setOnTimeChangedListener(TimePicker.OnTimeChangedListener { timePicker, hour, minute ->
            textView.text = "Hour: "+ hour + " Minute : "+ minute

When you run this Kotlin code example, you should get the following view on your screen:

TimePicker example in Kotlin


Don’t forget to check other Kotlin programming tutorials I have published in Kotlin category.

And if you are interested in learning Kotlin in more details, check out the below books and video lessons.

Happy learning Kotlin!

Building Mobile Apps with Kotlin for Android – Books

Building Mobile Apps with Kotlin for Android – Video Courses

Leave a Reply

Your email address will not be published. Required fields are marked *