Open In App

Dynamic TimePicker in Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

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 programmatically in Kotlin file.

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.

Modify activity_main.xml file

In this file, we use the LinearLayout inside the RelativeLayout, which is going to be accessed in the Kotlin file. Also set the attribute of the Layout like id, orientation etc.

xml




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
  
    </LinearLayout>
  
</RelativeLayout>


Update strings.xml file

Here, we update the name of the application using the string tag.

xml




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


Create TimePicker in MainActivity.kt file

First, we declare two variables txtView and timePicker to create the widgets.

val txtView = TextView(this)
val timePicker = TimePicker(this)

then, we should add them into the Linearlayout using

val linearLayout = findViewById(R.id.linear_layout)
        linearLayout?.addView(timePicker)
        linearLayout?.addView(txtView)

How to display time and its Logic already covered in previous topic.

Kotlin




package com.geeksforgeeks.myfirstKotlinapp
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.TimePicker
  
class MainActivity : AppCompatActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        //create textView from XML file
        val txtView = TextView(this)
        // create TimePicker programmatically
        val timePicker = TimePicker(this)
  
        val layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
  
        timePicker.layoutParams = layoutParams
        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 (txtView != 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"
                txtView.text = msg
                txtView.visibility = ViewGroup.VISIBLE
            }
        }
        val linearLayout = findViewById<LinearLayout>(R.id.linear_layout)
        linearLayout?.addView(timePicker)
        linearLayout?.addView(txtView)
    }
}


AndroidManifest.xml file

xml




<?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:

We can change the view by clicking on the icon in left bottom. To use text TimePicker click on keyboard icon and to use the Clock we should click on the clock icon.



Last Updated : 02 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads