TimePicker in Kotlin - GeeksforGeeks

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:
Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish.
Click on File, then New => New Project.
After that include the Kotlin support and click on next.
Select the minimum SDK as per convenience and click next button.
Then select the Empty activity => next => finish.
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
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
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>
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>
Here, we will specify the name of the activity.
<resources>    <string name="app_name">TimePickerInKotlin</string></resources>
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.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport 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            }        }    }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"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>
 
Android-Date-time
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android Project folder Structure
Broadcast Receiver in Android With Example
Different Ways to Change the Project Name in Android Studio
Fix “SDK tools directory is missing” Error in Android Studio
How to Retrieve Data from the Firebase Realtime Database in Android?
Android UI Layouts
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Kotlin Hashmap
How to Change the Color of Status Bar in an Android App?