Simple example using TextClock with Kotlin

TextClock can display the current date and/or time as a formatted string. It's a simple example of using TextClock with Kotlin.

layout XML with TextClock

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

<TextClock
android:id="@+id/mytextclock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic|bold"
android:textSize="40dp"
android:format12Hour="hh:mm:ss a"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

Access TextClock using Kotlin

package com.blogspot.android_er.androidtextclock

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextClock
import android.widget.Toast

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val myTextClock = findViewById<TextClock>(R.id.mytextclock)
myTextClock.setOnClickListener{
val s = myTextClock.text
Toast.makeText(this, s, Toast.LENGTH_LONG).show()
}

}
}


Post a Comment

Previous Post Next Post