android string顯示多樣式字…

SpannableString和SpannableStringBuilder都有一個設置上述Span的方法:

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

其中參數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 = new SpannableStringBuilder("abcdefghijklmn");

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

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

/ *圖片*/SpannableStringBuilder sBuilder = new SpannableStringBuilder(content);

 

Pattern pattern = Pattern.compile(m_strReg);

Matcher matcher = pattern.matcher(content);

Drawable drawable = null;

ImageSpan span = null;

String emo = "";

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),小於時縮小(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----如果設置了此風格,會有一條線從中間穿過所有的字,就像被劃掉一樣
對於這些Sytle span在使用的時候通常只傳上面所說明的構造參數即可,不需要設置其他的屬性,如果需要的話,也可以對它們設置其他的屬性。


java.lang.Object
   ↳ android.text.style.CharacterStyle
android <wbr>string顯示多樣式字體(TextView,EditText等顯示圖片文字)Known Direct Subclasses
android <wbr>string顯示多樣式字體(TextView,EditText等顯示圖片文字)Known Indirect Subclasses
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章