samaniego
samaniego

Reputation: 419

How to set TextColor on TextClock Android Compose

I want to change the color of TextClock in AndroidCompose, it is found as follows:

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

Upvotes: 0

Views: 925

Answers (2)

D.Y Won
D.Y Won

Reputation: 301

TextColor object itself doesn't have fuction to set color of the text. However as TextColor class extends TextView class and in it there is setTextColor function. In this setTextColor function we need to pass integer as per its indication. Now, for TextClock, Context object(=context) is already passed in and in this object there is getColor function where we can pass the color we want as integer.

The below code line also can be used.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setTextColor(context.getColor(R.color.white))
        }

Upvotes: 0

samaniego
samaniego

Reputation: 419

I finally found how, I post the code hoping it will be useful

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

Upvotes: 3

Related Questions