Jetpack 仅使用粗体字符串占位符

问题描述 投票:0回答:5

我有这样的字符串资源

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

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

我怎样才能得到想要的输出?

android android-jetpack-compose
5个回答
26
投票

最后我得到了想要的结果

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

0
投票

在我看来,我想出了一个更灵活和可重用的解决方案,因为如果我们有多个占位符,上面引用的解决方案将不起作用

@Composable
fun annotateRecursively(
    placeHolderList: List<Pair<String, SpanStyle>>,
    originalText: String
): AnnotatedString {
    var annotatedString = buildAnnotatedString { append(originalText) }
    for (item in placeHolderList) {
        annotatedString = buildAnnotatedString {
            val startIndex = annotatedString.indexOf(item.first)
            val endIndex = startIndex + item.first.length
            append(annotatedString)
            addStyle(style = item.second, start = startIndex, end = endIndex)
        }
    }
    return annotatedString
}

这基本上需要一个

Pair
的列表,精确到
placeholder
和一个
SpanStyle
(而不是
Pair
它可以是自定义
data class
如果你需要其他任何东西......)

然后遍历

list
以将
string
与相应的
SpanStyle
注释到它们的占位符。


-1
投票

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

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

-1
投票

之前的评论太复杂了。 在字符串资源中使用 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")
        }
    )

-1
投票

用这个

    @Composable
fun MultipleStylesInText() {
    Text(
        buildAnnotatedString {
            withStyle(style = SpanStyle(color = Color.Blue)) {
                append("H")
            }
            append("ello ")

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

输出 - outputImage

src - github /或/ developers

© www.soinside.com 2019 - 2024. All rights reserved.