Open In App
Related Articles

Dynamic TextClock in Kotlin

Like Article
Save Article
Report issue
Android TextClock is a user interface control which is used to show the date/time in string format. It provides time in two modes, first one is to show the time in 24 Hour format and another one is to show the time in 12 hour format. We can easily use is24HourModeEnabled() method, to show the system using TextClock in 24 Hours or 12 Hours format. Here, we will create the TextClock programmatically in the 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 TextView and Button and set attributes of all the widgets.


<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    <LinearLayout xmlns:android=""
        android:orientation="vertical" />
        android:text="Show Time" />


Update strings.xml file

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


    <string name="app_name">DynamicTextClockInKotlin</string>


Create TextClock in MainActivity.kt file

First, we a variable to create TextClock like this
val textClock = TextClock(this)
then, set the format of the clock display in the layout.
textClock.format12Hour = "hh:mm:ss a"
We have to add the textClock in the linear layout using
val linearLayout = findViewById(
        //add textClock in Linear Layout


package com.geeksforgeeks.myfirstkotlinapp
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextClock
import android.widget.TextView
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //create TextClock programmatically
        val textClock = TextClock(this)
        val layoutParams = LinearLayout.LayoutParams(
        layoutParams.setMargins(140, 80, 80, 80)
        textClock.layoutParams = layoutParams
        textClock.format12Hour = "hh:mm:ss a"
        val linearLayout = findViewById<LinearLayout>(
        //add textClock in Linear Layout
        val txtView = findViewById<TextView>(
        val btn = findViewById<Button>(
        // display time when click the button
        btn?.setOnClickListener {
            txtView?.text = "Time: " + textClock?.text


AndroidManifest.xml file


<?xml version="1.0" encoding="utf-8"?>
    <activity android:name=".MainActivity">
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />


Run as Emulator:


Last Updated : 28 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads