android string显示多样式字…

来源:互联网 发布:龙骑战歌 完整源码 编辑:程序博客网 时间:2024/06/04 19:59

SpannableString和SpannableStringBuilder都有一个设置上述Span的方法:

    
   setSpan(Object what, int start, int end, intflags);  

其中参数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所在的端点

例子:

/*字体*/SpannableStringBuilder ssb = newSpannableStringBuilder("abcdefghijklmn");

ssb.setSpan(newRelativeSizeSpan(0.4f), 0, 5,SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);

---------------------------------------------------------------------------

/*图片*/SpannableStringBuilder sBuilder = newSpannableStringBuilder(content);

 

Patternpattern = Pattern.compile(m_strReg);

Matchermatcher = pattern.matcher(content);

Drawabledrawable = null;

ImageSpanspan = null;

Stringemo = "";

while(matcher.find()) {

emo =matcher.group();

drawable= getDrawableByPicName(m_map.get(emo));

drawable.setBounds(0,0, (int)((float)m_screenWidth/Common.HDPI*24)+2,(int)((float)m_screenWidth/Common.HDPI*24)+2);

span =new ImageSpan(drawable);

sBuilder.setSpan(span,matcher.start(),matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

 

}


创建完Spannable对象后,就可以为它们设置Span来实现想要的Rich Text了,常见的Span有:

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),小于时缩小(zoomout)
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----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样
对于这些Sytlespan在使用的时候通常只传上面所说明的构造参数即可,不需要设置其他的属性,如果需要的话,也可以对它们设置其他的属性。


java.lang.Object   ↳android.text.style.CharacterStyleandroid <wbr>string显示多样式字体(TextView,EditText等显示图片文字)Known Direct Subclasses
BackgroundColorSpan, ClickableSpan, ForegroundColorSpan, MaskFilterSpan, MetricAffectingSpan, RasterizerSpan, StrikethroughSpan, SuggestionSpan,UnderlineSpan
android <wbr>string显示多样式字体(TextView,EditText等显示图片文字)Known Indirect Subclasses
AbsoluteSizeSpan, DynamicDrawableSpan, ImageSpan, LocaleSpan, RelativeSizeSpan, ReplacementSpan, ScaleXSpan, StyleSpan, SubscriptSpan, SuperscriptSpan,TextAppearanceSpan, TypefaceSpan, URLSpan
0 0
原创粉丝点击