What's the equivalent of TextClock in Jetpack Compose?

Viewed 548

TextClock is a widget for Android XML layouts which keeps and displays time on it's own. You just have to add the format and timezone.

Right now I don't see an equivalent in Jetpack Compose. Should I implement it by my own with a Text composable and some time formatting libraries? Should I inflate a TextClock and make use of the backwards compatibility? Or is there a ready to use component?

1 Answers

I started with using the original TextView by adding it via the AndroidView composable. It does work but I would still appreciate an answer without "legacy" code.

@Composable
private fun TextClock(
    modifier: Modifier = Modifier,
    format12Hour: String? = null,
    format24Hour: String? = null, 
    timeZone: String? = null,
) {
    AndroidView(
        factory = { context ->
            TextClock(context).apply {
                format12Hour?.let { this.format12Hour = it }
                format24Hour?.let { this.format24Hour = it }
                timeZone?.let { this.timeZone = it }
            }
        },
        modifier = modifier
    )
}
Related