Android的TextView与Html相结合的具体方法
Android的TextView与Html相结合的具体方法
发布时间:2016-12-28 来源:查字典编辑
摘要:Android中的TextView,本身就支持部分的Html格式标签。这其中包括常用的字体大小颜色设置,文本链接等。使用起来也比较方便,只需...

Android中的TextView,本身就支持部分的Html格式标签。这其中包括常用的字体大小颜色设置,文本链接等。使用起来也比较方便,只需要使用Html类转换一下即可。比如:

textView.setText(Html.fromHtml(str));

一、实现TextView里的文字有不同颜色

[plain]

复制代码 代码如下:

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代码。可以使用

[plain]

复制代码 代码如下:

Spanned text = Html.fromHtml(source);

tv.setText(text);

来实现,这个用起来简单方便。

但是,怎样让TextView也显示Html中<image>节点的图像呢?

我们可以看到fromHtml还有另一个重构:

复制代码 代码如下:

fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)

实现一下ImageGetter就可以让图片显示了:

[plain]

复制代码 代码如下:

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。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新安卓软件开发学习
热门安卓软件开发学习
编程开发子分类