androidfont-sizespannablestring

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 ?


Solution

  • 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);