第一种方法:Spannable
使用步骤:- SpannableString spannable = new SpannableString(str);
- // SpannableStringBuilder spannable = new SpannableStringBuilder(str);
- //创建各类Span
- CharacterStyle span=new UnderlineSpan();
- spannable.setSpan(span,start,end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
- //可以连续设置span
- view.setText(spannable);
void android.text.SpannableString.setSpan(Object what, int start, int end, int flags)
setSpan会将start到end这间的文本设置成创建的span格式。span可以是图片格式。
各类Span示例
- new URLSpan("http://www.baidu.com")
- new BackgroundColorSpan(Color.RED)
- new ForegroundColorSpan(Color.YELLOW)
- new StyleSpan(android.graphics.Typeface.BOLD_ITALIC)
- new UnderlineSpan();
- 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)
- TextView textView1 = (TextView) findViewById(R.id.textView1);
- TextView textView2 = (TextView) findViewById(R.id.textView2);
- //两次加大字体,设置字体为红色(big会加大字号,font可以定义颜色)
- textView1.setText(Html.fromHtml("北京市发布霾黄色预警,<font color='#ff0000'><big><big>外出携带好</big></big></font>口罩"));
textView_price.setText(Html.fromHtml(price.substring(0,price.indexOf("."))+"<small><small>"+price.substring(price.indexOf("."),price.length())+"</small></small>"));- //设置字体大小为3级标题,设置字体为红色
- textView2.setText(Html.fromHtml("北京市发布霾黄色预警,<h3><font color='#ff0000'>外出携带好</font></h3>口罩"));