【问题标题】:set background color black to only characters and white color between two characters TextView将背景颜色黑色设置为仅字符和两个字符之间的白色 TextView
【发布时间】:2018-05-24 10:33:20
【问题描述】:
【问题讨论】:
标签:
android
android-layout
textview
android-studio-2.2
android-text-color
【解决方案1】:
在这种情况下,您应该使用SpannableString。假设,你有这个String
A B C D E F G
并且您只需要在B 和E 字母下设置黑色背景。这可以通过这种方式实现(用 Kotlin 编写的示例):
fun highlight(text: String, words: List<String>) {
val spannable = SpannableString(text)
words.forEach {
var index = text.indexOf(it)
val length = it.length
while (index >= 0) {
highlightWord(spannable, index, length)
if (index >= 0) {
index += length
}
index = text.indexOf(it, index)
}
}
// TODO: set spannable to the TextView
}
fun highlightWord(spannable: Spannable, index: Int, length: Int) {
spannable.setSpan(BackgroundColorSpan(Color.BLACK), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
这里的方法highlight 在传递的文本中搜索传递的单词出现,并使用Color.BLACK 颜色突出显示每个出现。要使用白色突出显示空格,您可以通过传递 " " 空格字符串来执行相同操作,或者将白色背景设置为所有文本视图。