naiyu
naiyu

Reputation: 775

SpannableStringBuilder append a SpannableString object not show the span?

I am trying to use the SpannableStringBuilder to implement spannable color to all occurrence of a given character sequence in the sentence, just like:

val spannableStr1 = SpannableString("hello world!")
spannableStr1.setSpan(ForegroundColorSpan(Color.parseColor("#FF0000")),
        0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val spannableBuilder = SpannableStringBuilder()
spannableBuilder.append(spannableStr1)
spannableBuilder.append(spannableStr1)
tvDemo.text = spannableBuilder

and this resulted to:

enter image description here

I need the second occurrence of the characters hel also in red color. So I tried to append spannableStr1 again, but it seems not working.

Is there any way to implement it?

Upvotes: 2

Views: 1560

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93708

The span on spannableStr1 is set for 0-3. Unfortunately once you add it to the spannable string builder the second time, it's still 0-3. This causes the problem here- you colored the same part red twice.

A better way of doing this is not to add spans to the text. Instead, just append the text and add the spans directly to the SpannableStringBuilder. This means the first span should be (0,3) and the second one should be (index of second h, index of second h + 3)

val spannableStr1 ="hello world!"
val spannableBuilder = SpannableStringBuilder()
spannableBuilder.append(spannableStr1)
spannableBuilder.append(spannableStr1)
spannableBuilder.setSpan(ForegroundColorSpan(Color.parseColor("#FF0000")),
        0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableBuilder.setSpan(ForegroundColorSpan(Color.parseColor("#FF0000")),
        spannableStr1.length, spannableStr1.length + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
tvDemo.text = spannableBuilder

Upvotes: 3

Related Questions