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,並標識為超鏈接,可點擊,點擊后便跳轉到相應的應用。
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM