Android - 如何更改位于 string.xml 中的字符串的一部分的颜色?

Android - How can I change the color of a part of a String located in string.xml?

在我的应用程序(在 Kotlin 中)中,我的 string.xml 中有一个这样的字符串:<string name="buy_price">Buy %1$s %2$s for %3$s %4$s</string>

其中,例如 %1$s 是金额,%2$s 是项目名称,%3$s 是金额,%4$s 是法币名称。

我想为 %1$s、%2$s、%3$s...设置一些颜色。但我不知道如何。我一直在考虑像 5 个 textView 一样连接,它存储字符串的一部分,但它不是很干净 ...

你能帮帮我吗

你可以试试 Html.fromHtml

我相信你可以穿上 strings.xml 类似的东西:

<string name="buy_price">Buy &lt;span style='color:blue'>%1$s&lt;/span> &lt;span style='color:red'>%2$s&lt;/span> for &lt;span style='color:green'>%3$s&lt;/span> &lt;span style='color:yellow'>%4$s&lt;/span></string>

然后你打电话给textView.text = Html.fromHtml(getString(R.string.buy_price), 0)

Obs:在 strings.xml 中,我将 < 替换为 &lt;。这是一种解决方法,因为我相信 getString 会尝试解析 html 标签,例如 <b><u>.

Spannable 实现:

val category = "Monitor"
val item = "LG - 2562"
val currency = "Rs"
val amount = "1234"

val text = getString(R.string.buy_price, category, item, currency, amount)

val categoryColor = Color.BLUE
val categoryStart = text.indexOf(category)
val categoryEnd = categoryStart + category.length

val itemColor = Color.GREEN
val itemStart = text.indexOf(item)
val itemEnd = itemStart + item.length

val currencyColor = Color.RED
val currencyStart = text.indexOf(currency)
val currencyEnd = currencyStart + currency.length

val amountColor = Color.MAGENTA
val amountStart = text.indexOf(amount)
val amountEnd = amountStart + amount.length

textView.text = SpannableStringBuilder(text).apply {
    setSpan(
        ForegroundColorSpan(categoryColor),
        categoryStart,
        categoryEnd,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    setSpan(
        ForegroundColorSpan(itemColor),
        itemStart,
        itemEnd,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    setSpan(
        ForegroundColorSpan(currencyColor),
        currencyStart,
        currencyEnd,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
    setSpan(
        ForegroundColorSpan(amountColor),
        amountStart,
        amountEnd,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
}

结果:

Luiz 的回答有效(所以我不想要功劳!)但仅适用于一般调查此问题的任何人...

您可以将字符串的文本包裹在 HTML 标签中以设置样式。有两种显示方式:

  • 将其设置为 XML
  • 中的文本属性
  • 使用 Html.fromHtml(getString(R.string.whatever))
  • 在代码中设置

您可以使用两个标签:

  • <font color="#FF0000"></font> - 在代码中工作并且 XML

  • <span style="color:#FF0000"></span> - 在代码中工作,而不是 XML,可能允许更多样式。不要在样式位中添加空格![=2​​6=]


正如 Luiz 所说,您需要用 &lt; 替换 < 字符,这样 getString 就不会在 fromHtml 到达它们之前弄乱标签(它确实说 returns 文本“剥离样式信息”)。然而!

  • < - 被 getString 破坏,适用于 XML
  • &lt; - 在代码中工作,在 XML
  • 中中断(未解析为标记)

所以基本上:

  • 在代码中使用字符串?使用<font>标签style属性,将标签的开头<改为&lt;
  • 使用 XML 中的字符串?使用 <font> 标签并保留开头 <
  • 使用代码 XML 中的字符串?您可能需要两个版本来处理不同的开始标记字符!
  • 使用位置参数?你在代码中做到了

我没有使用过数据绑定所以我不能肯定地说,但我假设因为你是 运行 代码(刚刚在 XML 中定义)所有一般情况下,与 运行 代码相同的注意事项。