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。

上一篇:bzoj 1228: [SDOI2009]E&D 阿达马矩阵


下一篇:bzoj2338[HNOI2011]数矩形 计算几何