Android实现RichText(富文本)不同Text样式

同一个TextView里面显示不同风格的文字。
类似这种。
 
主要的基本工具类有android.text.Spanned; android.text.SpannableString; android.text.SpannableStringBuilder;
使用这些类来代替常规String。SpannableString和SpannableStringBuilder可以用来设置不同的Span,这些Span便是
用于实现Rich Text,比如粗体,斜体,前景色,背景色,字体大小,字体风格等。
 
 
使用:
当要显示Rich Text信息的时候,可以使用创建一个SpannableString或SpannableStringBuilder,它们的区别在于
SpannableString像一个String一样,构造对象的时候传入一个String,之后再无法更改String的内容,也无法拼接
多个SpannableString;而SpannableStringBuilder则更像是StringBuilder,它可以通过其append()方法来拼接
多个String。接着,可以直接把SpannableString和SpannableStringBuilder通过TextView.setText()设置给TextView。
  1. finalTextView textWithString =(TextView) findViewById(R.id.text_view_font_1);
    String w ="The quick fox jumps over the lazy dog";
    int start = w.indexOf('q');
    int end = w.indexOf('k')+1;
    Spannable word =newSpannableString(w);
    word.setSpan(newAbsoluteSizeSpan(22), start, end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
setSpan参数:
AbsoluteSizeSpan(int size) ---- 设置字体大小,参数是绝对数值,相当于Word中的字体大小;
 
RelativeSizeSpan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out);
 
ScaleXSpan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out) BackgroundColorSpan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.Color里面定义的常量,或是用Color.rgb(int, int, int);
 
ForegroundColorSpan(int color) ----前景着色,也就是字的着色,参数与背景着色一致 TypefaceSpan(String family) ----字体,参数是字体的名字比如“sans", "sans-serif"等;
 
StyleSpan(Typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.Typeface里面定义的常量,如Typeface.BOLD,Typeface.ITALIC等等。 StrikethroughSpan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样;
这里有个如果设置自定义的字体:要记得获取getStyle。
  1. privateTypeface mRegularTypeFace;
    mRegularTypeFace =Typeface.createFromAsset(getAssets(),"fonts/AvenirNext-Regular.ttf");
    word.setSpan(newStyleSpan(mBoldTypeFace.getStyle()), start, end,
    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    mMyLevel.setText(word);
参数what:
设置的Style span,start和end则是标识String中Span的起始位置,而 flags是用于控制行为的,通常设置为0或Spanned中定义的常量,
常用的有:
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE --- 不包含两端start和end所在的端点;
Spanned.SPAN_EXCLUSIVE_INCLUSIVE --- 不包含端start,但包含end所在的端点;
Spanned.SPAN_INCLUSIVE_EXCLUSIVE --- 包含两端start,但不包含end所在的端点;
Spanned.SPAN_INCLUSIVE_INCLUSIVE--- 包含两端start和end所在的端点;
 
Linkify :
另外,也可以对通过TextView.setAutoLink(int)设置其Linkify属性,其用处在于,TextView会自动检查其内容,
会识别出phone number, web address or email address,并标识为超链接,可点击,点击后便跳转到相应的应用。
 
 

 

posted @ 2015-08-21 14:20  咖啡馆的水果拼盘  阅读(4467)  评论(0编辑  收藏  举报