您的位置:首页 > 其它

怎么混合显示图片和文本

2014-06-17 11:21 351 查看
在有的Android应用中,需要在文字的中间插入一个图片,比如像下面图中所示的效果:



天气小图片显示在文字的后面,要实现此效果可以自己写一个View,但是也可以使用TextView结合android.text.Spanned来实现此效果。

Spanned的内容可以是一段html文本,图片就可以用img元素嵌入进去了,图片的内容可以根据img元素的src地址获取,也可以根据此src地址从保存在手机本地的资源文件里加载。下面是简单的示例代码:

TextView weather=(TextView) findViewById(R.id.weather);

Spanned info = null;

try

{

info = getWeather(defaultCity);

}

catch(Exception e){

}

if (info != null) {

weather.setText(info);

} else {

weather.setText("获取天气信息失败!");

}

Spanned getWeather(String city) {

String weatherData;//天气信息html片段

ImageGetter imgGetter = new Html.ImageGetter() {

@Override

public Drawable getDrawable(String url) {

Drawable drawable = null;

if (url.startsWith("/")) {

//图片url地址是个相对地址,需要变成绝对url地址

}

byte[] imgBuffer = null;

try {

//从网址url获取图片内容,保存在imgBuffer里

} catch (Exception e) {

return null;

}

String name = "";

int pos = url.lastIndexOf("/");

name = url.substring(pos + 1);//图片文件名

InputStream in = new ByteArrayInputStream(imgBuffer);

drawable = Drawable.createFromStream(in, name);//从输入流创建Drawable

try {

in.close();

} catch (IOException e) {

}

return drawable;

}

};

Spanned text = null;

try {

text = Html.fromHtml(weatherData, imgGetter, null);//创建一个Spanned

} catch (Exception e1) {

text = null;

}

return text;

}

代码比较简单。如果图片事先已经保存在资源文件里,那么就无需从网上去下载图片内容了,只需使用Drawable.createFromResourceStream这个方法从资源文件加载进来创建Drawable即可。

转自:http://blog.csdn.net/yelbosh/article/details/8039476
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: