Android TextView修改文字样式



一、 引出CharSequence接口
TextView.setText(CharSequence);

二、实现CharSequence接口
SpannableString、SpannableStringBuilder实现此接口,但是二者的区别是?


三、例子
String text = "Love_World_";  
SpannableString style = new SpannableString(text);      
style.setSpan(new ForegroundColorSpan(Color.RED),0,5,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
textView.setText(style);   

四、Spannable 接口能力
    SpannableString、SpannableStringBuilder这两个类同样实现Spannable接口,根据以上例子,查看下Spannable.setSpan方法
     public void setSpan(Object what, int start, int end, int flags);
    
     此方法有4个参数,其中第二个与第三个是需要设置样式的文字在字符串中的起止位置。
     以下注重介绍下第一个参数,接收对象时Object,其支持的所有样式可以在官方文档查询http://developer.android.com/reference/android/text/style/package-summary.html
     里面大多都是针对API LEVEL 1的,仅有API LEVEL 14新增 EasyEditSpan、SuggestionSpan, API LEVEL 17新增 LocaleSpan 、API LEVEL 21新增TtsSpan

ForegroundColorSpan指定文字颜色传入的参数有以下四种写法,其中需要注意的是第一种方式0x后面一定紧跟两个ff表示透明度的,没有会被解析为00即透明看不到效果。
new ForegroundColorSpan (0xffeeeeee) // 必须有ff 透明值
new ForegroundColorSpan (Color. parseColor("#eeeeee" ))
new ForegroundColorSpan (Color.RED)
new ForegroundColorSpan (getResources().getColor(r.color.name))

字体TypefaceSpan、添加删除线StrikethroughSpan、设置字体TypefaceSpan

参考资料:
http://blog.csdn.net/hitlion2008/article/details/6856780


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。