joshas
joshas

Reputation: 1474

Add multiple styles at once to SpannableString

Currently, I'm setting text and background colors for a part of string using SpannableString like so:

SpannableStringBuilder spanString = new SpannableStringBuilder(text);
spanString.setSpan( new ForegroundColorSpan(Color.RED), start, end, 0 );
spanString.setSpan( new BackgroundColorSpan(Color.GRAY), start, end, 0 );

Is there any way to combine both of those styles into one CharacterStyle object and set it to text in one command?

Upvotes: 8

Views: 3706

Answers (1)

erin
erin

Reputation: 1160

If you ultimately want to set the text of a TextView (or something similar), you can use SpannableString to format each string separately and use TextUtils.concat to patch them together, which removes the need for a SpannableStringBuilder.

The code below set the text in the TextView to "Hello World" where "Hello" is red and "World" is green.

TextView myTextView = new TextView(this);
SpannableString myStr1 = new SpannableString("Hello");
SpannableString myStr2 = new SpannableString("World");
myStr1.setSpan( new ForegroundColorSpan(Color.RED), 0, myStr1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myStr2.setSpan( new ForegroundColorSpan(Color.GREEN), 0, myStr2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myTextView.setText(TextUtils.concat(myStr1, " ", myStr2));

Upvotes: 8

Related Questions