Android TextView修改文字樣式,androidtextview
一、 引出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