Access TextClock in MainActivity.kt file
First, we declare two variables txtClock and txtView to access the widgets from the XML layout using the id.
val txtClock = findViewById<TextClock>(R.id.txtClok) val txtView = findViewById<TextView>(R.id.textview)
then, we access the button and set OnClickListener to display the time while clicking the button.
val btn = findViewById<Button>(R.id.btn) btn?.setOnClickListener { txtView?.text = "Time: " + txtClock?.text
Kotlin
package com.w3wiki.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextClock import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) val txtClock = findViewById<TextClock>(R.id.txtClok) val txtView = findViewById<TextView>(R.id.textview) val btn = findViewById<Button>(R.id.btn) btn?.setOnClickListener { txtView?.text = "Time: " + txtClock?.text } } } |
TextClock in Kotlin
Android TextClock is a user interface control that is used to show the date/time in string format.
It provides time in two modes, the 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.
First, we create a new project by following the below steps:
- Click on File, then New => New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click next button.
- Then select the Empty activity => next => finish.