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="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearLayout"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.appsdeveloperblog.kotlinexample3.TimePickerExample">

</LinearLayout>

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.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.TimePicker

class TimePickerExample : AppCompatActivity() {

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_time_picker_example)
        val linearLayout = findViewById(R.id.linearLayout) as LinearLayout


        val textView = TextView(this)
        linearLayout.addView(textView)

        val timePicker = TimePicker(this)
        linearLayout.addView(timePicker)

        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 *