Heleena Joy
Heleena Joy

Reputation: 119

How to give different color to a part of sentence?

I have a sentence. For eg: "ABCD is a place where i live. ABCD is known for tourism". I need to give the 2nd "ABCD" a blue color and set this whole sentence to a textview.The thing is -the word which needs to be colored is dynamic, we will get the word from response. and if the word is repeating in sentence and if i need to give a particular one(suppose i get the position from response) a blue color, what is the practical way.

var title2 = "ABCD is a place where i live. ABCD is known for tourism"
var title3 = "ABCD"
var spannableString = SpannableString(title2)
                spannableString.setSpan(
                    ForegroundColorSpan(Color.BLUE),
                    title2.indexOf(title3),
                    title2.indexOf(title3)+title3.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
textview.text = spannableString

So according to my code,only 1st ABCD gets blue color. But I need to give only the 2nd "ABCD" a blue color

Upvotes: 1

Views: 42

Answers (1)

Ivo
Ivo

Reputation: 23277

indexOf returns the first occurence of the specified string. To get the second, you can indicate the index from where to start searching from as second argument of indexOf. For example like

var spannableString = SpannableString(title2)
                spannableString.setSpan(
                    ForegroundColorSpan(Color.BLUE),
                    title2.indexOf(title3, 1),
                    title2.indexOf(title3, 1) + title3.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )

If the first occurence isn't at the start of the String you could write this instead

var spannableString = SpannableString(title2)
                spannableString.setSpan(
                    ForegroundColorSpan(Color.BLUE),
                    title2.indexOf(title3, title2.indexOf(title3) + 1),
                    title2.indexOf(title3, title2.indexOf(title3) + 1) + title3.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )

Upvotes: 1

Related Questions