android-jetpack-composeandroid-jetpack-compose-text

Monospace numbers in the Jetpack Compose Text component


I'm using a custom font within my Jetpack Compose app and would like to monospace the numbers within a specific Text component.

With standard Android TextView, this can be done using the fontFeatureSetting="tnum" attribute (https://stackoverflow.com/a/41143337/2521749).

How can you do this with Jetpack Compose?

Countdown clock


Solution

  • buildAnnotatedString is needed to customize different parts of a string.

    If you need to apply some text style to the whole Text, you can use style argument.

    Text(
        text = String.format(Locale.ROOT, "%02d:%02d", mins, secs),
        style = LocalTextStyle.current.copy(fontFeatureSettings = "tnum"),
    )
    

    I'm using LocalTextStyle.current here, which is the default style for Text, but you can replace it with the one you need, like one of your theme typography: MaterialTheme.typography.h4