Home > Enterprise >  How does Text("Hello") display font color when I use Jetpack Compose with default settings
How does Text("Hello") display font color when I use Jetpack Compose with default settings

Time:08-29

I create a project with the wizard Empty Compose Activity of Android Studio. I use Text("Hello") to display a text.

I know the font size of the text is 16.sp by looking source code, but how can I know which color is displayed of the text?

BTW, I look at the source code , the color of font is specified as Color.Unspecified, I don't know what color will be displayed for Color.Unspecified.

Source Code

// Set of Material typography styles to start with
val Typography = Typography(
    body1 = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp
    )
    ...
)


class TextStyle
@OptIn(ExperimentalTextApi::class)
internal constructor(
    ...
) {
    ...
    @OptIn(ExperimentalTextApi::class)
    constructor(
        color: Color = Color.Unspecified,
        fontSize: TextUnit = TextUnit.Unspecified,
    ...
}


val Unspecified = Color(0f, 0f, 0f, 0f, ColorSpaces.Unspecified)

CodePudding user response:

If we look at the source code of Text composable, we can find,

val textColor = color.takeOrElse {
    style.color.takeOrElse {
        LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
    }
}
  1. Here color is the argument passed to the Text composable, which defaults to Color.Unspecified if no color is passed.

We see a method takeOrElse is used.

takeOrElse definition

inline fun Color.takeOrElse(block: () -> Color): Color = if (isSpecified) this else block()

Color.isSpecified definition

inline val Color.isSpecified: Boolean get() = value != Color.Unspecified.value

In other words, we can read this code as set textColor as the color if it is not equal to Color.Unspecified, else use the value in the given lambda.

Since we already know the color is Color.Unspecified if no color is specified (from above point 1), the value in the lambda will be used.

Value in lambda

The lambda checks if there is a color in the style TextStyle provided (either by user or by default value LocalTextStyle.current). If there is one, it will be used. Else the value of the below will be used.

LocalContentColor.current.copy(alpha = LocalContentAlpha.current)

LocalContentColor, LocalContentAlpha and LocalTextStyle are provided using CompositionLocalProvider.

CodePudding user response:

The color in the Text is defined by the color parameter or applying a TextStyle. The default value is enter image description here

And if you assign a Color

Text("Hello World",
    color = Color.Red,
    onTextLayout = {
        it.layoutInput.style.color
    }
)

enter image description here

  • Related