The Wayback Machine - https://web.archive.org/web/20240912170031/https://www.geeksforgeeks.org/timepicker-in-kotlin/
Open In App

TimePicker in Kotlin

Last Updated : 19 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Attributes Description
android:id Used to uniquely identify the control.
android:timePickerMode Used to specify the mode of TimePickerpicker(spinner or clock)
android:background Used to set background color of the Text View.
android:padding Used to set the padding from left, right, top and bottom.
android:visibility Used 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:

 



Previous Article
Next Article

Similar Reads

Dynamic TimePicker in Kotlin
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 a 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. In this article, we should create TimePicker widget
3 min read
TimePicker in Android
TimePicker Dialog is used in many applications where we have to book appointments based on a specific time. This widget is seen in the applications where we have to select specific time slots. In this article, we will take a look at How to use TimePicker Dialog on Android. Note: This Android article covered in both Java and Kotlin languages. Step b
4 min read
TimePicker.OnTimeChangedListener() in Android
onTimeChangedListener is a method that is called when time is edited or changed inside a TimePicker. TimePicker is an essential class provided by Android Developers. The callback interface is used to indicate the time has been adjusted. It can be helpful for providing instantaneous clock field responses. Syntax For Java: public abstract void onTime
3 min read
Implement customized TimePicker in Android using SnapTimePicker
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 a valid time for the day in the application. The default TimePicker can be customized by using the SnapTimePicker in Android. Some features of SnapTimePicker are:Selectable time range support.Text and co
3 min read
Kotlin Data Types
The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects. There are different data types in Kotlin: Integer Data typeFloating-point Data
3 min read
Hello World program in Kotlin
Hello, World! is the first basic program in any programming language. Let's write the first program in Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. // Kotlin Hello World Program fun main(args: Array&lt;String&gt;) { pri
2 min read
Android Shared Element Transition with Kotlin
Shared element transition is seen in most of the applications which are used when the user navigates between two screens. This type of animation is seen when a user clicks on the items present in the list and navigates to a different screen. During these transitions, the animation which is displayed is called a shared element transition. In this ar
4 min read
Kotlin | Retrieve Collection Parts
The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying the start and end indices of the sublist. The result
5 min read
Destructuring Declarations in Kotlin
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables correspond to the properties of a class that are associat
3 min read
DatePicker in Kotlin
Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePic
3 min read
Kotlin labelled continue
In this article, we will learn how to use continue in Kotlin. While working with a loop in the programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. Basically, continue is used to repeat the loop for a specific condition. It skips the following statements a
4 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. Step by Step Implementation 1. If you observe the ab
7 min read
Kotlin Exception Handling | try, catch, throw and finally
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions - Checked Exceptio
6 min read
A Complete Guide to Learn Kotlin For Android App Development
Kotlin is a statically typed, cross-platform, general-purpose programming language for JVM developed by JetBrains. This is a language with type inference and fully interoperable with Java. Kotlin is concise and expressive programming as it reduces the boilerplate code. Since Google I/O 2019, Android development has been Kotlin-first. Kotlin is seam
8 min read
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the condi
4 min read
Android - Save ArrayList to SharedPreferences with Kotlin
SharedPreferences is local storage in android which is used to store data in the form of key and value pairs within the android devices. We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin. A sample video is given b
9 min read
Create an Android App that Displays List of All Trending Kotlin git-hub Repositories
Kotlin is a popular programming language that has gained much attention in recent years. It is known for its simplicity, conciseness, and compatibility with existing Java code. GitHub is a popular platform for hosting and sharing code, including Kotlin projects. This article will discuss how to build an application that shows a list of Kotlin GitHu
12 min read
Kotlin Environment setup for Command Line
To set up a Kotlin environment for the command line, you need to do the following steps: Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin compiler: You can download the latest version of the
2 min read
Kotlin Environment setup with Intellij IDEA
Kotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully interoperable with Java code. Let's see how to setu
2 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year: Int inner class Engine { var horsepower: Int = 0
5 min read
Android - Line Graph View with Kotlin
Graphs are used in android applications to display vast amounts of data in an easily readable form. There are different types of graphs used such as BarGraph, GroupBar graph, point, and line graph to represent data. In this article, we will take a look at How to use Line Graph View in Android using Kotlin. A sample video is given below to get an id
3 min read
Working with Anonymous Function in Kotlin
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it can
3 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example + and - are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operatorRelation operatorAssignment operatorUnary operatorLogical operatorBitwise operator Arithmetic Operators - Op
3 min read
Kotlin Standard Input/Output
In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence of bytes or byte streams from input device such as Keyboard to the main memory of the system and from main memory to output device such as Monitor. In Java, we use System.out.pr
5 min read
Kotlin Expression, Statement and Block
Kotlin Expression - An expression consists of variables, operators, methods calls etc that produce a single value. Like other language, Kotlin expression is building blocks of any program that are usually created to produce new value. Sometimes, it can be used to assign a value to a variable in a program. It is to be noted that an expression can co
4 min read
Kotlin for loop
In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines. While loop - It consists of a block of code and a condition. First
2 min read
Kotlin do-while loop
Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes
2 min read