首页 > 解决方案 > Jetpack compose 中的 ClickableText 样式

问题描述

我正在尝试更改可点击文本的样式,主要是它的字体和颜色。

我现在正在使用:

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

This just using the default theme.

How can I apply a different color or font or fontsize ? 

Thanks

标签: androidandroid-jetpackandroid-jetpack-compose

解决方案


要使用字体,请定义一个fontFamily属性,如下所示

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

然后将其添加到您的排版中

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

添加到您的主题中

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

如果您随后在文本中使用这些样式,它将选择您指定的系列,或者您可以覆盖,像这样

Text(
    text = "Sample text",
    style = MaterialTheme.typography.body1.copy(
        color = Color.Blue,
        fontFamily = Montserrat,
    ),
)

推荐阅读