Text Clock is a UI widget in android which is used to display the current time in android applications. This widget displays the current time in a simple text view. The text clock widget displays a time in 12 and 24 hours format. In this article, we will take a look at How to use the TextClock widget on android using Jetpack Compose.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Comments are added inside the code to understand the code in more detail.
In this file, we will be using the AndroidView composable to integrate the xml view, TextClock in compose.
MainActivity,kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import android.widget.TextClock
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.unit.*
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import com.geeksforgeeks.demo.ui.theme.DemoTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoTheme {
DisplayTextClock()
}
}
}
}
@Composable
fun DisplayTextClock() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Android view composable to use xml views in compose
AndroidView(
factory = { context ->
// Text Clock
TextClock(context).apply {
// set hour format
format12Hour = "hh:mm:ss a"
// set time zone
timeZone = timeZone
// set text size
textSize= 32f
// set text color
setTextColor(ContextCompat.getColor(context, R.color.black))
}
},
modifier = Modifier.padding(5.dp),
)
}
}