set background color black to only characters and white color between two characters TextView

736 views Asked by At

how do i set background color black to only characters and white background color between the characters in only single TextView android studio Example in image

Like in image it shows A is having background color black and the space between A and B is having white background color. How can to achieve it?

enter image description here

enter image description here

1

There are 1 answers

0
Demigod On

In this case you should use SpannableString. Assume, you have this String

A B C D E F G

and you need to set black background only under B and E letters. This could be achieved in this way (examples written in 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)
}

Here method highlight searches passed words occurrences in passed text and highlights every occurrence using Color.BLACK color. To highlight spaces with white color you can do the same by passing " " space String, or just set the white background to all text view.