本文转自:
http://blog.csdn.net/zhang957411207/article/details/7741972
先看截图:
![Android TextView使用HTML处理字体样式、显示图片等(转) - Gobby.X - Just Miss.Gobby](http://img1.ph.126.net/fr__N_0I2tqSUqfm7ZnE0A==/6598279229447660350.png)
* Sets the string value of the TextView. TextView <em>does not</em> accept
* HTML-like formatting, which you can do with text strings in XML resource files.
* To style your strings, attach android.text.style.* objects to a
* {@link android.text.SpannableString SpannableString}, or see the
* <a href=" {@docRoot}guide/topics/resources/available-resources.html#stringresources">
* Available Resource Types</a> documentation for an example of setting
* formatted text in the XML resource file.
*
* @attr ref android.R.styleable#TextView_text
*/
@android.view.RemotableViewMethod
public final void setText(CharSequence text) {
setText(text, mBufferType);
}
android.text.Html类共提供了三个方法,可以到Android帮助文档查看。
public static Spanned fromHtml (String source)
public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
public static String toHtml (Spanned text)
通过使用第一个方法,可以将Html显示在TextView中:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.textView1);
String html="<html><head><title>TextView使用HTML</title></head><body><p><strong>强调</strong></p><p><em>斜体</em></p>"
+"<p><a href=\"http://www.dreamdu.com/xhtml/\">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1"
+"</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" +
"下面是网络图片</p><img src=\"http://avatar.csdn.net/0/3/8/2_zhang957411207.jpg\"/></body></html>";
tv.setMovementMethod(ScrollingMovementMethod.getInstance());//滚动
tv.setText(Html.fromHtml(html));
}
效果:
![Android TextView使用HTML处理字体样式、显示图片等(转) - Gobby.X - Just Miss.Gobby](http://img0.ph.126.net/VdMAoD5T20T2EHwqpOjJww==/6597631617099110082.png)
修改后的代码:
public Drawable getDrawable(String source) {
Drawable drawable = null;
URL url;
try {
url = new URL(source);
drawable = Drawable.createFromStream(url.openStream(), ""); //获取网路图片
} catch (Exception e) {
return null;
}
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
return drawable;
}
};
不要忘了在Mainifest文件中加入网络访问的权限:
上面介绍的是显示网络上的图片,但如何显示本地的图片呢:
ImageGetter imgGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
Drawable drawable = null;
drawable = Drawable.createFromPath(source); //显示本地图片
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
return drawable;
}
};
String source;
source=getFilesDir()+"/ic_launcher.png";