Android TimePicker Using Kotlin With Example

In this article, we will learn about android TimePicker using Kotlin. We will go through various example that demonstrates how to use different attributes of TimePicker. For example,

In this article, we will get answer to questions like –

  • What is TimePicker?
  • Why should we consider TimePicker while designing ui for any app?
  • What are possibilities using TimePicker while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin TimePicker Output Android TimePicker Using Kotlin

Tutorialwing Kotlin TimePicker Output

Getting Started

We can define android TimePicker widget as below –

TimePicker is widget to select time in either 24-hour format or AM/PM format.

Now, how do we use TimePicker in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as TimePicker. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android TimePicker Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using TimePicker in Kotlin

Follow steps below to use TimePicker in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">TimePicker</string>
        <string name="selected_time">The selected time is:</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TimePicker
            android:id="@+id/timePicker"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="40dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="40dp"
            android:visibility="gone"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/timePicker" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.timepicker
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View
    import com.tutorialwing.timepicker.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupTimePicker()
    	}
    
    	private fun setupTimePicker() {
    		binding.timePicker.setOnTimeChangedListener { _, hourOfDay, minute ->
    			val dayHour = when {
    				hourOfDay == 0 -> {
    					hourOfDay + 12
    				}
    				hourOfDay > 12 -> {
    					hourOfDay - 12
    				}
    				else -> hourOfDay
    			}
    
    			val format = when {
    				hourOfDay >= 12 -> {
    					"PM"
    				}
    				else -> "AM"
    			}
    
    			val hour = if (dayHour < 10) "0$dayHour" else dayHour
    			val min = if (minute < 10) "0$minute" else minute
    
    			val text = getString(R.string.selected_time) + " " + hour + " : " + min + " " + format
    			binding.textView.text = text
    			binding.textView.visibility = View.VISIBLE
    		}
    	}
    }
    

Now, run the application. We will get output as below –

Tutorialwing Kotlin TimePicker Output Android TimePicker Using Kotlin

Tutorialwing Kotlin TimePicker Output

Different Attributes of TimePicker in XML

Now, we will see how to use different attributes of Android TimePicker using Kotlin to customise it –

Set Id of TimePicker

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of TimePicker using android:id attribute like below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        />

Here, we have set id of TimePicker as timePicker_ID using android:id=”” attribute. So, if we need to reference this TimePicker, we need to use this id – timePicker_ID.
Learn to Set ID of TimePicker Dynamically

Set Width of TimePicker

We use android:layout_width=”” attribute to set width of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of TimePicker Dynamically

Set Height of TimePicker

We use android:layout_height=”” attribute to set height of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of TimePicker Dynamically

Set Padding of TimePicker

We use android:padding=”” attribute to set padding of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in TimePicker using android:padding=”” attribute.
Learn to Set Padding of TimePicker Dynamically

Set Margin of TimePicker

We use android:layout_margin=”” attribute to set margin of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in TimePicker using android:layout_margin=”” attribute.
Learn to Set Margin of TimePicker Dynamically

Set Background of TimePicker

We use android:background=”” attribute to set background of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in TimePicker using android:background=”” attribute.
Learn to Set Background of TimePicker Dynamically

Set Visibility of TimePicker

We use android:visibility=”” attribute to set visibility of TimePicker.
We can do it as below –

    <TimePicker
        android:id="@+id/timePicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of TimePicker using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of TimePicker Dynamically

Till now, we have see how to use android TimePicker using Kotlin. We have also gone through different attributes of TimePicker to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android TimePicker Widget

Below are the various attributes that are used to customise android TimePicker Widget. However, you can check the complete list of attributes of TimePicker in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Attributes of android TimePicker widget are –

Sr. XML Attributes Description
1 android:timePickerMode Defines look of the TimePicker widget

Some of the popular attributes of TimePicker inherited from FrameLayout are –

Sr. XML Attributes Description
1 android:foregroundGravity Sets the gravity of the foreground drawable
2 android:measureAllChildren When measuring, It specifies whether to measure all children or only those that are in visible or invisible state

Some of the popular attributes of TimePicker inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animationCache Specifies whether layout animations should create a drawing cache for their children.
2 android:layoutAnimation Specifies the layout animation to use the first time the ViewGroup is laid out
3 android:layoutMode Specifies the layout mode

Some of the popular attributes of TimePicker inherited from View are –

Sr. XML Attributes Description
1 android:background Specifies background of the view
2 android:clickable Specifies whether view is clickable or not
3 android:fadeScrollbars Specifies whether scrollbar should fade out when not in use or not
4 android:fitsSystemWindows Specifies whether to adjust view layout according to system windows
5 android:id Specifies id of the view
6 android:minHeight Specifies minimum height
7 android:minWidth Specifies minimum width
8 android:padding Specifies padding of the view
9 android:paddingBottom Specifies padding to bottom of the view
10 android:paddingEnd Specifies padding to end of the view
11 android:visibility Specifies visibility of the view

We have seen different attributes of TimePicker and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is TimePicker, how can we use android TimePicker using Kotlin ? etc. We also went through different attributes of android TimePicker.

Leave a Reply

We are actively looking for Paid Content Writer. Email us at tutorialwing@gmail.com if you are interested.