【问题标题】:How to set TextColor on TextClock Android Compose如何在 TextClock Android Compose 上设置 TextColor
【发布时间】:2022-12-24 12:50:46
【问题描述】:
我想在AndroidCompose中改变TextClock的颜色,找到如下:
@Composable
fun displayClock() {
Column(
Modifier
.fillMaxSize()
.fillMaxHeight()
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
AndroidView(
factory = { context ->
TextClock(context).apply {
format12Hour?.let { this.format12Hour = "hh:mm:ss a" }
timeZone?.let { this.timeZone = it }
textSize.let { this.textSize = 30f }
}
},
modifier = Modifier.padding(5.dp),
)
}
}
【问题讨论】:
标签:
android
kotlin
textcolor
【解决方案1】:
我终于找到了方法,我发布了代码希望它会有用
@Composable
fun displayClock() {
Column(
Modifier
.fillMaxSize()
.fillMaxHeight()
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
AndroidView(
factory = { context ->
val style = R.style.Theme_Assistant
TextClock(ContextThemeWrapper(context, style), null, style).apply {
format12Hour?.let { this.format12Hour = "hh:mm:ss a" }
timeZone?.let { this.timeZone = it }
textSize.let { this.textSize = 40f }
setTextColor(ContextCompat.getColor(context, R.color.orange))
}
},
modifier = Modifier.padding(5.dp),
)
}
}
【解决方案2】:
TextColor 对象本身没有设置文本颜色的功能。但是,由于 TextColor 类扩展了 TextView 类,并且其中有 setTextColor 函数。在此 setTextColor 函数中,我们需要根据其指示传递整数。
现在,对于 TextClock,上下文对象 (=context) 已经传入,并且在这个对象中有 getColor 函数,我们可以在其中将我们想要的颜色作为整数传递。
也可以使用下面的代码行。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setTextColor(context.getColor(R.color.white))
}