Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClickableText styling in jetpack compose

I am trying to change the style of a clickable text, mostly its font and color. Here's my code:

ClickableText(
    text = AnnotatedString(stringResource(R.string.forgot_password)),
    onClick = { offset ->
        Log.d("ClickableText", "$offset -th character is clicked.")
    }
)

This is just using the default theme. How can I apply a different color or font?

like image 444
Seb Avatar asked Sep 12 '25 21:09

Seb


2 Answers

It offers the style parameter. You could just do something like

ClickableText(
    text = AnnotatedString(""),
    onClick = {},
    style = TextStyle(
        color = Blue,
        fontSize = 26.sp,
        fontFamily = FontFamily.Cursive
    )
)

If you are using Android Studio, you can just press Ctrl + P on Windows and Cmd + P on Mac to check the available parameters. The optional parameters are not inserted by code completion since they can be many.

like image 136
MARSK Avatar answered Sep 15 '25 13:09

MARSK


To use fonts, define a fontFamily property, like this

private val Montserrat = FontFamily(
    Font(R.font.montserrat_regular, FontWeight.Normal),
    Font(R.font.montserrat_medium, FontWeight.Medium),
    Font(R.font.montserrat_bold, FontWeight.Bold),
)

then add it to your Typography

val Typography = Typography(
    h1 = TextStyle(
        fontFamily = Montserrat,
        fontSize = 96.sp,
        fontWeight = FontWeight.Normal,
        lineHeight = 117.sp,
        letterSpacing = (-1.5).sp
    ),

which is added to your theme

MaterialTheme(
    colors = colors,
    typography = Typography,
    shapes = Shapes,
    content = content
)

If you then use these styles in your text it will pick the family you specified, or you can override, like this

Text(
    text = "Sample text",
    style = MaterialTheme.typography.body1.copy(
        color = Color.Blue,
        fontFamily = Montserrat,
    ),
)
like image 25
Francesc Avatar answered Sep 15 '25 12:09

Francesc