1、TextView 显示 Html 类解析的网页
CharSequence richText = Html.fromHtml("<strong>萝卜白菜的博客</strong>--<a href='http://orgcent.com'>http://orgcent.com</a>");
mTVText.setText(richText);
// 此行必须,否则超链接无法点击,ScrollingMovementMethod 实现滚动条
mTVText.setMovementMethod(LinkMovementMethod.getInstance());
PS:如果想同时让内容可滚动和超链接可点击,只要设置 LinkMovementMethod 即可,因为其继承了 ScrollingMovementMethod。
2、TextView 显示 Html 解析的图片和自定义标签
final String html = "萝卜白菜的博客<img src='http://m3.img.libdd.com/farm3/115/BBE681F0CAFB16C6806E6AEC1E82D673_64_64.jpg'/><mytag color='blue'>自定义
</mytag>";
// 处理未知标签,通常是系统默认不能处理的标签
final Html.TagHandler tagHandler = new Html.TagHandler() {
int contentIndex = 0;
/**
* opening : 是否为开始标签
* tag: 标签名称
* output:输出信息,用来保存处理后的信息
* xmlReader: 读取当前标签的信息,如属性等
*/
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if ("mytag".equals(tag)) {
if (opening) { // 获取当前标签的内容开始位置
contentIndex = output.length();
try {
final String color = (String) xmlReader.getProperty("color");
} catch (Exception e) {
e.printStackTrace();
}
} else {
final int length = output.length();
String content = output.subSequence(contentIndex, length).toString();
SpannableString spanStr = new SpannableString(content);
spanStr.setSpan(new ForegroundColorSpan(Color.GREEN), 0, content.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
output.replace(contentIndex, length, spanStr);
}
}
System.out.println("opening:" + opening + ",tag:" + tag + ",output:" + output);
}};
// 解析图片
final Html.ImageGetter imageGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
// 在此必须异步加载图片
Drawable d = null;
try {
InputStream is = new DefaultHttpClient().execute(new HttpGet(source)).getEntity().getContent();
Bitmap bm = BitmapFactory.decodeStream(is);
d = new BitmapDrawable(bm);
// setBounds(0, 0, bm.getWidth(), bm.getHeight());
d.setBounds(0, 0, 200, 300);
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
};
}
richText = Html.fromHtml(html, imageGetter, tagHandler);
mTVText.setText(richText);
转载自:
http://orgcent.com/android-textview-parse-html-image-tag/