使用最少数量的字符串。
一种方法是按如下方式定义颜色:
颜色.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 可以根据需要应用于每种语言。