2

Within a TagHandler which I passed to Html.fromHtml(), I would like to append some formatted text to the given Editable output object, which then gets passed to a TextView.

Appending plain text with output.append("my text") works fine. But how to append red or italic text?

class MyTagHandler implements Html.TagHandler {

  @Override
  public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
    output.append("my text");
    // how to append red and italic text here ?
  }

}
Witek
  • 6,160
  • 7
  • 43
  • 63

2 Answers2

2

You should be able to use Html.fromHtml and Editable.setSpan() to do it. Here's some sample code:

    appendFormatted(output, "<font color=red><i>red italic</i></font>");
}

private void appendFormatted(Editable text, String string) {
    final int start = text.length();
    final Spanned span = Html.fromHtml(string);
    text.append(span);
    final int end = text.length();
    for (final Object o : span.getSpans(0, span.length(), Object.class)) {
        text.setSpan(o, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

If you just need some simple formatting applied, you can pass in the specific CharacterStyle derived-object to the Editable.setSpan() call - see the "Selecting, Highlighting, or Styling Portions of Text" example on the developers site.

Joe
  • 14,039
  • 2
  • 39
  • 49
1

If I understood your question right here is a way to do this

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
            "<small>" + description + "</small>" + "<br />" + 
            "<small>" + DateAdded + "</small>"));

The answer was copied from a similar question here.

Community
  • 1
  • 1
Shadow
  • 6,161
  • 3
  • 20
  • 14