【问题标题】:Android text Partial colouringAndroid 文字局部着色
【发布时间】:2022-12-15 00:31:41
【问题描述】:
    <string name="id">1. Tap <b><font fgcolor='#FF000000'>More</font></b> in the top-right corner.</string>

我希望“更多”用粗体和不同的颜色突出显示。这适用于灯光模式,但在夜间模式下 -> 我希望能够使用不同的颜色。最好的方法是什么?

(我知道 spannables ,但问题是......如果我使用带有索引的 spannable 文本,它不会适用于多种语言)

【问题讨论】:

  • 创建两个字符串:一个在灯光模式字符串 XML 中,具有灯光模式的颜色,一个在夜间模式字符串 XML 中,具有不同的颜色。文本将是相同的。
  • 我确实有同样的想法……但是,我将有很多需要维护的字符串文件。
  • 为什么会有很多字符串文件?因为语言多?
  • 是的。现在我有10种语言,但我想支持更多
  • 你要处理多少种颜色?只有两种,或者每种语言可以有两种独特的颜色,一种代表深色,一种代表浅色?

标签: android xml android-layout string-formatting


【解决方案1】:

这些似乎是要求:

  1. 支持多种语言。
  2. 每种语言至少有一个字符串,该字符串的颜色和粗体将应用于字符串文本的一部分,具体取决于应用程序是在“夜间”还是“浅色”模式下运行。
  3. “夜间”和“灯光”模式将各自使用一种颜色,这种颜色与上面 2) 中定义的其他模式不同。
  4. 使用最少数量的字符串。

    一种方法是按如下方式定义颜色:

    颜色.xml

    <color name="my_light_dark_color">#FFFF0000</color>
    

    colors.xml(晚上)

    <color name="my_light_dark_color">#FFFFFFFF</color>
    

    对于“夜间”模式,“白色”将是使用的颜色。否则,它将是“红色的”。

    在适当的“字符串”资源文件中定义字符串,并标记将使用颜色应用的部分注解跨越。下面我以英语和法语为例。

    字符串.xml

    <string name="hello_string">Hello! How are <b><annotation color="my_light_dark_color">you?</annotation></b></string>
    

    strings.xml(法语)

    <string name="hello_string">Bonjour! Comment allez-<b><annotation color="my_light_dark_color">vous</annotation></b>?</string>
    

    现在我们的资源已经到位,我们需要一些代码将它们拼接在一起。

    val textToColor = binding.textView.text.toSpannable()
    val lightDarkColor =
            ResourcesCompat.getColor(resources, R.color.my_light_dark_color, requireActivity().theme)
    
    // Find all Annotation spans that specifies a color as a key with the right value.
    textToColor.getSpans<android.text.Annotation>(0, textToColor.length)
        .filter { it.key == "color" && it.value == "my_light_dark_color"}.forEach {
            replaceSpan(textToColor, it, ForegroundColorSpan(lightDarkColor))
        }
    binding.textView.text = textToColor
    
    fun replaceSpan(spannable: Spannable, oldSpan: Any, newSpan: Any) {
        val spanStart = spannable.getSpanStart(oldSpan)
        val spanEnd = spannable.getSpanEnd(oldSpan)
        val flags = spannable.getSpanFlags(oldSpan)
        spannable.removeSpan(oldSpan)
        spannable.setSpan(newSpan, spanStart, spanEnd, flags)
    }
    

    上面的代码需要为要应用的文本颜色定义两个值,并为每种语言定义一个字符串。 Annotation span 可以根据需要应用于每种语言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    相关资源
    最近更新 更多