Android系統顯示HTML網頁的最佳控件為WebView,有時候為了滿足特定需求,需要在TextView中顯示HTML網頁、圖片及解析自定義標簽。
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。關於ScrollingMovementMethod說明,可查看android實現TextView垂直或水平滾動
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);