繁体   English   中英

Jetpack Compose 中的 TextClock 相当于什么?

[英]What's the equivalent of TextClock in Jetpack Compose?

TextClock是一个用于 Android XML 布局的小部件,它可以自行保存和显示时间。 您只需添加格式和时区。

现在我在 Jetpack Compose 中看不到等效项。 我应该使用可组合文本和一些时间格式化库自己实现它吗? 我应该膨胀 TextClock 并利用向后兼容性吗? 或者有现成的组件吗?

我开始使用原始 TextView,方法是通过 AndroidView 可组合添加它。 它确实有效,但我仍然希望没有“遗留”代码的答案。

@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
    )
}

这是我的解决方案,它使样式成为可能。

@Composable
fun ClockText() {
    val currentTimeMillis = remember {
        mutableStateOf(System.currentTimeMillis())
    }

    LaunchedEffect(key1 = currentTimeMillis) {
        while (true) {
            delay(250)
            currentTimeMillis.value = System.currentTimeMillis()
        }
    }

    Box() {
        Text(
            text = DateUtils.formatDateTime(LocalContext.current, currentTimeMillis.value, DateUtils.FORMAT_SHOW_TIME),
            modifier = Modifier.padding(8.dp, 8.dp),
            color = MaterialTheme.colors.onBackground,
            style = MaterialTheme.typography.subtitle2
        )
    }
}

https://gist.github.com/dino-su/c8edf1c206dd974b282326f3b9641ccc

TextClock 类扩展了 TextView 类,TextView 类扩展了 View 类。 但是,Jetpack Compose 并非基于“视图”。 因此,我试图找到在 Compose 中使用视图的方法,并找到了这个链接。

https://developer.android.com/jetpack/compose/interop/interop-apis#views-in-compose

该链接解释了 AndroidView 的可组合性。 在 Android 文档的 TextClock 页面中,我可以阅读“荣誉 24 小时格式系统设置”,因此检查用户设置是否基于 12 小时格式就足够了。 我的示例代码如下,圣诞快乐!

@Composable
fun MyTextClock() {
    AndroidView(factory = { context ->
        TextClock(context).apply {
            format12Hour?.let {
                this.format12Hour = "a hh: mm: ss"
            }
            timeZone?.let { this.timeZone = it }
            textSize.let { this.textSize = 24f }
        }
    })
}

@Preview(showBackground = true)
@Composable
fun MyTextClockPreview() {
    MyTextClock()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM