使用Spannable或Html.fromHtml设置字体、颜色、超链接等

来源:互联网 发布:mac地址一样 修改 编辑:程序博客网 时间:2024/05/23 17:43


第一种方法:Spannable

使用步骤:
  1. SpannableString spannable = new SpannableString(str);
  2. // SpannableStringBuilder spannable = new SpannableStringBuilder(str);
  3. //创建各类Span
  4. CharacterStyle span=new UnderlineSpan(); 
  5. spannable.setSpan(span,start,end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
  6. //可以连续设置span
  7. view.setText(spannable);

void android.text.SpannableString.setSpan(Object what, int start, int end, int flags)

setSpan会将start到end这间的文本设置成创建的span格式。span可以是图片格式。

各类Span示例

  1. new URLSpan("http://www.baidu.com")
  2. new BackgroundColorSpan(Color.RED)
  3. new ForegroundColorSpan(Color.YELLOW)
  4. new StyleSpan(android.graphics.Typeface.BOLD_ITALIC)
  5. new UnderlineSpan(); 
  6. new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

第二种方法:Html.fromHtml()

只显示带文本的html可以用下面的方法处理html文件。

public static Spanned fromHtml (String source)  

显示带图片的html要用下面的方法处理html文件。

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

ImageGetter 为处理html中<img>的处理器,生成Drawable对象并返回。 

创建ImageGetter 主要实现下面的方法,source为<img>标签中src属性的值。

public Drawable getDrawable(String source)
  1. TextView textView1 = (TextView) findViewById(R.id.textView1);  
  2. TextView textView2 = (TextView) findViewById(R.id.textView2);  
  3.   
  4. //两次加大字体,设置字体为红色(big会加大字号,font可以定义颜色)  
  5. textView1.setText(Html.fromHtml("北京市发布霾黄色预警,<font color='#ff0000'><big><big>外出携带好</big></big></font>口罩"));  
  6.   
  7. //设置字体大小为3级标题,设置字体为红色  
  8. textView2.setText(Html.fromHtml("北京市发布霾黄色预警,<h3><font color='#ff0000'>外出携带好</font></h3>口罩"));  
2 0