Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple styles at once to SpannableString

Tags:

android

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?

like image 440
joshas Avatar asked Jan 18 '12 18:01

joshas


People also ask

Can you have multiple styles inside TextView?

There are many ways to make multiple styles inside android TextView and in this example I have made multiple style with three different ways using HTML tags and Html. fromHtml().

What is Spannable string in Android?

Text styling is one of the important aspects when it comes to enhancing the UI of an Android application. In Android, we can change the size, color, weight, style, etc of a text and make the text more attractive and appealing.

What is Spanned in Android?

Spanned -> immutable text with immutable markup. Spannable (extends Spanned )-> immutable text with mutable markup. Apply a span by calling setSpan(Object what, int start, int end, int flags) on the Spannable object. The what Object is the marker that will be applied from a start to an end index in the text.


1 Answers

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));
like image 151
erin Avatar answered Oct 08 '22 19:10

erin