Reputation: 9778
I have a piece of HTML I want to highlight. It's not a predefined piece of text, so it has to be dynamic.
I have a SpannableString
that has a lot of html, but I would like to style the <pre>
tags and <code>
tags. Could I do this using some standard Java API or Android API, or will I have to use some sort of Regex to match those tags?
I have tried something like this:
public static void styleSpans(String markdownString) {
Spannable raw = new SpannableString(markdownString);
BackgroundColorSpan[] spans = raw.getSpans(0, raw.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index = TextUtils.indexOf(raw, "<pre>");
}
and do something with the index of those tags, but I need an example to know what I'm actually doing. How could I do this?
Upvotes: 1
Views: 1040
Reputation: 1675
Regexp is one way to do this.
Matcher matcher = Pattern.compile("<pre>(.+?)</pre>", Pattern.DOTALL).matcher(markdownString);
// use matcher object to construct Spannable
Alternatively, class android.text.Html
has method fromHtml(String, Html.ImageGetter, Html.TagHandler)
but it converts all tags it can to Spans. Tags <pre>
and <code>
are unsupported so they are passed to android.text.Html.TagHandler.handleTag(boolean, String, Editable, XMLReader)
which you must override. There you can add appropriate spans and even extra text yourself. Probably the best place to learn how to write support for different tags into handleTag is the source code of inner class android.text.Html.HtmlToSpannedConverter
. In your case this seems to be too heavy-weight as you need to strip a lot of Spans for displaying all other tags just in plain text.
Third option is to use SAX Parser. I think it's the best option and it is used internally in Html.fromHtml()
. Here is one tutorial: http://www.verious.com/tutorial/android-sax-parsing-example/. Create Handler where you define only <pre>
and <code>
. Parser should consume those tags and just tell you when the tag begins (so you can mark start of Span), the it gives you contents of the tag, and finally it tells you when the tag ends (close your Span there). For all other tags just append the contents to Spannable
Upvotes: 1