//處理未知標籤,一般是系統默認不能處理的標籤
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);