Method for rendering simple HTML fragments
I am writing an Android app for accessing StackExchange and I am looking for the best way to handle rendering the simple HTML fragments used in the StackExchange API. The only HTML in the API are in the bodies of questions, answers, and comments. Comments, of course, use a more restricted subset of HTML. Most of the HTML is just simple formatting like <p>
, <b>
, <pre>
, etc. but there are also <a>
and the occasional <img>
tag to deal with. I was considering just trying to use a TextView and replace the HTML with styling, but that might be too restrictive. I took a look at WebView, but that almost seems overkill. WebViews seem to be 开发者_运维百科for loading external dynamic content and start multiple threads. I'm only planning on rendering simple, fixed HTML provided in the API which does not include any CSS or JavaScript.
Also, I'm having an encoding issue with WebViews where characters like curly quotes show up as multiple characters where they display fine when used in a TextView.
What you can do is use the Html.fromHtml()
function.
It will leave you with a Spanned
- type object. You might use the seperate spans on the locations to handle the tags?
An example to edit tags. Situations: a text with html tags, that work using html.fromhtml. But sometimes the urls are relative (using "/file.html" instead of "http://domain.com/file.html") and so it can't be used. Sending the spannable to my function below finds all spans for a URL and adds the domain. You could use somehting else ofcourse for your specific tags:
protected Spanned correctLinkPaths (Spanned spantext) {
Object[] spans = spantext.getSpans(0, spantext.length(), Object.class);
for (Object span : spans) {
int start = spantext.getSpanStart(span);
int end = spantext.getSpanEnd(span);
int flags = spantext.getSpanFlags(span);
if (span instanceof URLSpan) {
URLSpan urlSpan = (URLSpan) span;
if (!urlSpan.getURL().startsWith("http")) {
if (urlSpan.getURL().startsWith("/")) {
urlSpan = new URLSpan("http://www.domain.com" + urlSpan.getURL());
} else {
urlSpan = new URLSpan("http://www.domain.com/" + urlSpan.getURL());
}
}
((Spannable) spantext).removeSpan(span);
((Spannable) spantext).setSpan(urlSpan, start, end, flags);
}
}
return spantext;
}
I'm not sure this is the most efficient way to do it, is was one of my first connections to spannables, but at least it shows some tricks you can do with spannables :D
精彩评论