繁体   English   中英

Jetpack 撰写仅粗体字符串占位符

[英]Jetpack compose bold only string placeholder

我有这样的字符串资源

<string name="my_string">Fancy string with an %1$s placeholder</string>

我想把它作为输出:“带有惊人占位符的花式字符串”。 这是占位符内容以粗体显示的字符串。

如何获得所需的输出?

假设您在可组合的文本中显示它,请执行此操作。 确保在 $ 字符前包含一个反斜杠:

Row(modifier = Modifier.wrapContentWidth()) {
    val s = LocalContext.current.getString(R.string.my_string)
    val p = s.indexOf("%1\$s")
    Text(s.substring(0, p))
    Text("amazing", fontWeight = FontWeight.Bold)
    Text(s.substring(p + 4))
}

最后我得到了想要的结果

val placeholder = "Amazing"

val globalText = stringResource(id = R.string.my_string, placeholder)

val start = globalText.indexOf(placeholder)
val spanStyles = listOf(
    AnnotatedString.Range(SpanStyle(fontWeight = FontWeight.Bold),
        start = start,
        end = start + placeholder.length
    )
)
Text(text = AnnotatedString(text = globalText, spanStyles = spanStyles))

以前的评论太复杂了。 在字符串资源中使用 html 标签就足够了:

<string name="my_string">Fancy string with an <b>amazing</b> <i>placeholder</i></string>

如果您使用 Composable - 您可以在某些情况下使用 buildAnnotatedString。 文档在这里

Text(
        buildAnnotatedString {
            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                append("W")
            }
            append("orld")
        }
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM