Thursday, May 12, 2011

Modifying (coloring, scaling) part of the text in the TextView

Thre are several ways to modify different parts of text in a single TextView. One of them is Html.fromHtm() that would format your text according to html tags you put in it beforehand. I find that approach too crude. You have to modify the original text manually to put opening and closing tags in, which can become really ugly if you need to do a lot of formatting.

The second way, is to use Spans and SpannableStringBuilder.
Spans give you ability to define modification, for example: new ForegroundColorSpan(Color.rgb(100, 100, 100)) can be used to change the color of the text. Similarly, new RelativeSizeSpan(0.8F) can be used to scale text.

SpannableStringBuilder allows us to apply those spans on particular areas of our text. Usage is very easy as demonstrated below:

private final static StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
private final static ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(100, 100, 100));
private final static RelativeSizeSpan rszSmall = new RelativeSizeSpan(0.8F);
private final static RelativeSizeSpan rszBig = new RelativeSizeSpan(1.2F);

private void insertFormattedText(final TextView view, final String text) {
  final SpannableStringBuilder sb = new SpannableStringBuilder(text);  

  // Make characters from 0 to 2 bold  
  sb.setSpan(bss, 0, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  // Change the color of characters from 2 to 4
  sb.setSpan(fcs, 2, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);   

  // Scale down characters from 4 to 6
  sb.setSpan(rszSmall, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE);   

  // Make characters from 6 to 8 bold
  sb.setSpan(bss, 6, 8, Spannable.SPAN_INCLUSIVE_INCLUSIVE);   

  // Scale up characters from 8 to 12
  sb.setSpan(rszBig, 8, 12, Spannable.SPAN_INCLUSIVE_INCLUSIVE);   

  // Set the text into the TextView
  view.setText(sb);
}

Spannable.SPAN_INCLUSIVE_INCLUSIVE points that both (ending and starting) characters must be included in formatting.

Just look into android.text.style.* package for a list of available spans ;)

No comments:

Post a Comment