簡體   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