将背景颜色设置为黑色,仅设置字符和两个字符TextView之间的白色

时间:2018-05-24 10:33:20

标签: android android-layout textview android-studio-2.2 android-text-color

如何将背景颜色设置为黑色,仅在单个TextView android studio Example in image

中的字符之间设置字符和白色背景颜色

在图像中,它表示A的背景颜色为黑色,A和B之间的空间为白色背景颜色。怎么能实现呢?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

在这种情况下,您应该使用SpannableString。假设您有String

A B C D E F G

,您只需在BE字母下设置黑色背景。这可以通过这种方式实现(用 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颜色突出显示每次出现的事件。要突出显示白色空间,您可以通过传递" "空格字符串来执行相同操作,或者只需将白色背景设置为所有文本视图。