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


第一种方法: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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值