我正在使用Html.fromHtml()在 TextView 中显示一些简单的 Html。就我的口味而言,<h2>
标题的字体有点太大了,所以我想知道如何做到这一点,Html 类没有相应的方法。我将深入研究源代码,看看我是否可以扩展一个类、覆盖一个方法或其他东西,但也许有人已经实现了为某些 Html 标签设置字体大小?
问问题
1129 次
1 回答
3
It is certianly possible. You just have to use Html.fromHtml()
with your own Handler sent with it.
You could do it like this:
CharSequence html = Html.fromHtml(markdownString, null, new TitleHandler());
...
static class TitleHandler implements TagHandler {
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if (tag.equalsIgnoreCase("h2")) {
processH2(opening, output);
}
}
public void processH2(boolean opening, Editable output) {
int len = output.length();
if (opening) {
output.setSpan(new RelativeSizeSpan(0.8f), len, len,
Spannable.SPAN_MARK_MARK);
} else {
Object obj = getLast(output, RelativeSizeSpan.class);
int where = output.getSpanStart(obj);
output.removeSpan(obj);
if (where != len) {
output.setSpan(new RelativeSizeSpan(0.8f), where, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for (int i = objs.length; i > 0; i--) {
if (text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) {
return objs[i - 1];
}
}
return null;
}
}
}
Using new RelativeSizeSpan(0.8f)
, you draw the Span
in the TextView
inside the <h2>
elements with a relative size of 80% as it is now.
All the HTML tag handlers of Android are also defined like this.
于 2013-08-09T08:54:15.297 回答