Skip to content
Related Articles

Related Articles

TimePicker in Kotlin
  • Last Updated : 19 Feb, 2021

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.

In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode.

We can use TimePicker manually in XML layout or we can create it programmatically in Kotlin file. In this article, we should use TimePicker widget in XML Layout.

First we create a new project by following the below steps:

  1. Click on File, then New => New Project.
  2. After that include the Kotlin support and click on next.
  3. Select the minimum SDK as per convenience and click next button.
  4. Then select the Empty activity => next => finish.

Android TimePicker with Clock mode

We can use android:timePickerMode to show only clock view. In the below example, we are using the TimePicker in clock mode.






<TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:timePickerMode="clock"/>

The above code of TimePicker can be seen in android application like this

Android TimePicker with Spinner mode

We can also use the TimePicker in spinner format by using android:timePickerMode attribute.




<TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:timePickerMode="spinner"/>

The above code of TimePicker can be seen in android application like this

Different attributes of TimePicker control –

XML AttributesDescription
android:idUsed to uniquely identify the control.
android:timePickerModeUsed to specify the mode of TimePickerpicker(spinner or clock)
android:backgroundUsed to set background color of the Text View.
android:paddingUsed to set the padding from left, right, top and bottom.
android:visibilityUsed to specify the visibility of the view.

To use Clock TimePicker in activity_main.xml

In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file.




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/padding"
        android:timePickerMode="clock"/>
  
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/timePicker"
        android:textSize="18dp"
        android:paddingLeft="80dp" />
  
</RelativeLayout>

To use Spinner TimePicker in activity_main.xml

In this file, we will add the TimePicker and TextView widget and set their attributes so that it can be accessed in the kotlin file.




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/padding"
        android:timePickerMode="spinner"/>
  
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/timePicker"
        android:textSize="18dp"
        android:paddingLeft="80dp" />
  
</RelativeLayout>

Modify the strings.xml file to add the string-array

Here, we will specify the name of the activity.




<resources>
    <string name="app_name">TimePickerInKotlin</string>
</resources>

Access the TimePicker in MainActivity.kt file

First of all, we define a function OnClickTime() and called from MainActivity.

private fun OnClickTime()

then, we declare two variables textView and timePicker to access the widgets from the XML layout using their id’s.

val textView = findViewById(R.id.textView)
val timePicker = findViewById(R.id.timePicker)




package com.geeksforgeeks.myfirstkotlinapp
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.*
  
class MainActivity : AppCompatActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        OnClickTime()
    }
  
    private fun OnClickTime() {
        val textView = findViewById<TextView>(R.id.textView)
        val timePicker = findViewById<TimePicker>(R.id.timePicker)
        timePicker.setOnTimeChangedListener { _, hour, minute -> var hour = hour
            var am_pm = ""
            // AM_PM decider logic
            when {hour == 0 -> { hour += 12
                am_pm = "AM"
            }
                hour == 12 -> am_pm = "PM"
                hour > 12 -> { hour -= 12
                    am_pm = "PM"
                }
                else -> am_pm = "AM"
            }
            if (textView != null) {
                val hour = if (hour < 10) "0" + hour else hour
                val min = if (minute < 10) "0" + minute else minute
                // display format of time
                val msg = "Time is: $hour : $min $am_pm"
                textView.text = msg
                textView.visibility = ViewGroup.VISIBLE
            }
        }
    }
}

AndroidManifest.xml file




<?xml version="1.0" encoding="utf-8"?>
package="com.geeksforgeeks.myfirstkotlinapp">
  
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
  
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
  
</manifest>

Run as Emulator:

 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :