萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> Android的TextView與Html結合用法

Android的TextView與Html結合用法

 Android中的TextView,本身就支持部分的Html格式標簽。這其中包括常用的字體大小顏色設置,文本鏈接等。使用起來也比較方便,只需要使用Html類轉換一下即可。比如:
textView.setText(Html.fromHtml(str));
一、實現TextView裡的文字有不同顏色
import android.text.Html;

TextView t3 = (TextView) findViewById(R.id.text3);
t3.setText(Html.fromHtml( "<b>text3:</b> Text with a " + "<a href="http://www.google.com">link</a> " +"created in the Java source code using HTML."));
二、TextView顯示html文件中的圖片
我們知道要讓TextView解析和顯示Html代碼。可以使用
Spanned text = Html.fromHtml(source);
tv.setText(text);
來實現,這個用起來簡單方便。
但是,怎樣讓TextView也顯示Html中<image>節點的圖像呢?
我們可以看到fromHtml還有另一個重構:
fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
實現一下ImageGetter就可以讓圖片顯示了:
ImageGetter imgGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = null;
drawable = Drawable.createFromPath(source); // Or fetch it from the URL
// Important
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
return drawable;
}
};
至於TagHandler,我們這裡不需要使用,可以直接傳null。

copyright © 萬盛學電腦網 all rights reserved