声明html
此文章为转载,并且写的还算不错。。java
结构android
继承关系web
public class Html extends Object浏览器
java.lang.Objectide
android.text.Html函数
类概述测试
该类主要用来格式化html格式的文本,像浏览器同样对html标签进行解析,渲染输出,但并非全部的标签都被支持!(译者注:固然你自定义的标签默认确定不被支持,但能够经过实现Html.TagHandler这个接口来自我解析。下面会讲到。)字体
内部类spa
interface Html.ImageGetter
用来检索HTML中的<img>标签。(译者注:若是实现了这个接口,当解析的时候遇到<img> 标签时会回调ImageGetter的getDrawable(String source)方法,并返回一个Drawable对象,该方法参数为<img>标签的src属性的值)
interface Html.TagHandler
用来通知当解析器遇到没法识别的标签时该做出何种处理
公共方法
public static Spanned fromHtml (String source)
返回经过TagSoup (TagSoup 是一个Java开发符合SAX的HTML解析器 受权协议)解析器解析以后的可直接显示的文本,任何<img>则由默认的通常图片所替代,固然也能够经过实现Html.ImageGetter接口来显示真正的图片。
参数
source 待处理的html文本
public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
同上,不一样的是当遇到img标签,或解析器没法识别的标签时分别触发注册的两个对象来进行处理。
参数
source 为待处理的html文本
imageGetter Html.ImageGetter对象
tagHandler Html.TagHandler 的
public static String toHtml (Spanned text)
该方法彻底能够理解为fromHtml()的可逆函数,将Spanned 类型的文本还原为HTML文本。
示例代码
public class Main extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.demo);
// 貌似都不支持HTML标签的属性,及CSS样式,下面使用到的字体颜色都不被支持 //String html = "<h2>html测</h2><pstyle='color:red;'>这是测试内容</p><p><imgsrc='http://www.baidu.com/img/baidu_sylogo1.gif'></p>"; String html = "<h2>html测试</h2><p font='red'>这是测试内容</p><p><img src='http://www.baidu.com/img/baidu_sylogo1.gif'></p>";
tv.setText(Html.fromHtml(html,newHtml.ImageGetter(){
@Override public Drawable getDrawable(String source) { Drawable myDrawable = null; try { myDrawable = Drawable.createFromStream(newURL(source).openStream(), "baidu_sylogo1.gif"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
return myDrawable; }},null)); }
} |