Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multiple spans on a TextView's text on the same partial text?

Suppose I have the next text :

Hello stackOverflow

And I wish to set the second word to be both RelativeSizeSpan (to set a relative font size) and TextAppearanceSpan (to set the color of the text) , how do I merge them both ?

All I know is that I can choose one of them , using the next code for example :

final SpannableString textToShow = new SpannableString("Hello stackOverflow"); textToShow.setSpan(new RelativeSizeSpan(1.5f), textToShow.length() - "stackOverflow".length(),textToShow.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(textToShow); 

But I need to also set the color , or even add other features from other spanning classes ...

What can I do ?

like image 885
android developer Avatar asked Feb 20 '13 13:02

android developer


People also ask

What is Spannable string in Android?

↳ android.text.SpannableString. This is the class for text whose content is immutable but to which markup objects can be attached and detached. For mutable text, see SpannableStringBuilder .

What is text spans?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.

What is Span_exclusive_exclusive?

SPAN_EXCLUSIVE_EXCLUSIVE. They are all the same! The flags don't affect the span. A span always includes the character at its start index and excludes the character at the end index.

How do I make string bold on Android?

Way 1 – make Android TextView bold using android:textStyle attribute. android:textStyle attribute is the first and one of the best way to make the text in TextView bold. just use “bold”. If you want to use bold and italic.


1 Answers

Simply set additional spans. They are going to overlap/merge when neccessary. This code works for me:

final SpannableString text = new SpannableString("Hello stackOverflow"); text.setSpan(new RelativeSizeSpan(1.5f), text.length() - "stackOverflow".length(), text.length(),             Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); text.setSpan(new ForegroundColorSpan(Color.RED), 3, text.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(text); 
like image 82
Zielony Avatar answered Oct 02 '22 15:10

Zielony