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 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 Kotin file. Also set the attribute of the Layout like id, orientation etc.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Update strings.xml file

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



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
    }
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.