【问题标题】:set background color black to only characters and white color between two characters TextView将背景颜色黑色设置为仅字符和两个字符之间的白色 TextView
【发布时间】:2018-05-24 10:33:20
【问题描述】:

如何在只有单个 TextView android studio Example in image 中将背景颜色黑色设置为仅字符和字符之间的白色背景色

如图所示,A 具有黑色背景色,A 和 B 之间的空间具有白色背景色。如何实现?

enter image description here

【问题讨论】:

  • 这里的问题是什么?你到底想问什么?

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


【解决方案1】:

在这种情况下,您应该使用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 颜色突出显示每个出现。要使用白色突出显示空格,您可以通过传递 " " 空格字符串来执行相同操作,或者将白色背景设置为所有文本视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 2017-09-04
    • 2011-10-08
    • 2014-10-20
    • 2011-01-15
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    相关资源
    最近更新 更多