1. 程式人生 > >Android實戰技巧:用TextView實現Rich Text---在同一個TextView中設定不同的字型風格

Android實戰技巧:用TextView實現Rich Text---在同一個TextView中設定不同的字型風格

背景介紹

在開發應用過程中經常會遇到顯示一些不同的字型風格的資訊猶如預設的LockScreen上面的時間和充電資訊。對於類似的情況,可能第一反應就是用不同的多個TextView來實現,對於每個TextView設定不同的字型風格以滿足需求。

這裡推薦的做法是使用android.text.*;和android.text.style.*;下面的元件來實現RichText:也即在同一個TextView中設定不同的字型風格。對於某些應用,比如文字編輯,記事本,彩信,簡訊等地方,還必須使用這些元件才能達到想到的顯示效果。

主要的基本工具類有android.text.Spanned; android.text.SpannableString; android.text.SpannableStringBuilder;使用這些類來代替常規String。SpannableString和SpannableStringBuilder可以用來設定不同的Span,這些Span便是用於實現Rich Text,比如粗體,斜體,前景色,背景色,字型大小,字型風格等等,android.text.style.*

中定義了很多的Span型別可供使用。

這是相關的API的Class General Hierarchy:

因為Spannable等最終都實現了CharSequence介面,所以可以直接把SpannableString和SpannableStringBuilder通過TextView.setText()設定給TextView。

使用方法

當要顯示Rich Text資訊的時候,可以使用建立一個SpannableString或SpannableStringBuilder,它們的區別在於SpannableString像一個String一樣,構造物件的時候傳入一個String,之後再無法更改String的內容,也無法拼接多個SpannableString;而SpannableStringBuilder則更像是StringBuilder,它可以通過其append()方法來拼接多個String:

[java] view plaincopyprint?
  1. SpannableString word = new SpannableString("The quick fox jumps over the lazy dog");  
  2. SpannableStringBuilder multiWord = new SpannableStringBuilder();  
  3. multiWord.append("The Quick Fox");  
  4. multiWord.append("jumps over");  
  5. multiWord.append("the lazy dog");  
建立完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在使用的時候通常只傳上面所說明的構造引數即可,不需要設定其他的屬性,如果需要的話,也可以對它們設定其他的屬性,詳情可以參見文件
SpannableString和SpannableStringBuilder都有一個設定上述Span的方法: [java] view plaincopyprint?
  1. /** 
  2.  * Set the style span to Spannable, such as SpannableString or SpannableStringBuilder 
  3.  * @param what --- the style span, such as StyleSpan 
  4.  * @param start --- the starting index of characters to which the style span to apply 
  5.  * @param end --- the ending index of characters to which the style span to apply 
  6.  * @param flags --- the flag specified to control 
  7.  */
  8. 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所在的端點

這裡理解起來就好像數學中定義區間,開區間還是閉區間一樣的。還有許多其他的Flag,可以參考這裡。這裡要重點說明下關於引數0,有很多時候,如果設定了上述的引數,那麼Span會從start應用到Text結尾,而不是在start和end二者之間,這個時候就需要使用Flag 0。

Linkify

另外,也可以對通過TextView.setAutoLink(int)設定其Linkify屬性,其用處在於,TextView會自動檢查其內容,會識別出phone number, web address or email address,並標識為超連結,可點選,點選後便跳轉到相應的應用,如Dialer,Browser或Email。Linkify有幾個常用選項,更多的請參考文件

  • Linkify.EMAIL_ADDRESS -- 僅識別出TextView中的Email在址,標識為超連結,點選後會跳到Email,傳送郵件給此地址
  • Linkify.PHONE_NUMBERS -- 僅識別出TextView中的電話號碼,標識為超連結,點選後會跳到Dialer,Call這個號碼
  • Linkify.WEB_URLS-- 僅識別出TextView中的網址,標識為超連結,點選後會跳到Browser開啟此URL
  • Linkify.ALL -- 這個選項是識別出所有系統所支援的特殊Uri,然後做相應的操作

權衡選擇

個人認為軟體開發中最常見的問題不是某個技巧怎麼使用的問題,而是何時該使用何技巧的問題,因為實現同一個目標可能有N種不同的方法,就要權衡利弊,選擇最合適的一個,正如常言所云,沒有最好的,只有最適合的。如前面所討論的,要想用不同的字型展現不同的資訊可能的解法,除了用Style Span外還可以用多個TextView。那麼就需要總結下什麼時候該使用StyleSpan,什麼時候該使用多個TextView:

  1. 如果顯示的是多個不同類別的資訊,就應該使用多個TextView,這樣也方便控制和改變各自的資訊,例子就是預設LockScreen上面的日期和充電資訊,因為它們所承載不同的資訊,所以應該使用多個TextView來分別呈現。
  2. 如果顯示的是同一類資訊,或者同一個資訊,那麼應該使用StyleSpan。比如,簡訊息中,要把聯絡人的相關資訊突出顯示;或是想要Highlight某些資訊等。
  3. 如果要實現Rich text,沒辦法,只能使用Style span。
  4. 如果要實現某些特效,也可以考慮使用StyleSpan。設定不同的字型風格只是Style span的初級應用,如果深入研究,可以發現很多奇妙的功效。

例項

[html] view plaincopyprint?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3.   xmlns:android="http://schemas.android.com/apk/res/android"
  4.   android:layout_width="wrap_content"
  5.   android:layout_height="wrap_content"
  6.   android:orientation="vertical">
  7.   <ScrollView
  8.     android:layout_width="fill_parent"
  9.     android:layout_height="wrap_content">
  10.         <LinearLayout
  11.             android:layout_width="fill_parent"
  12.             android:layout_height="wrap_content"
  13.             android:orientation="vertical">
  14.               <TextView
  15.                 android:id="@+id/text_view_font_1"
  16.                 android:layout_width="fill_parent"
  17.                 android:layout_height="wrap_content"
  18.                 />
  19.               <TextView
  20.                 android:id="@+id/text_view_font_2"
  21.                 android:layout_width="fill_parent"
  22.                 android:layout_height="wrap_content"
  23.                 />
  24.               <TextView
  25.                 android:id="@+id/text_view_font_3"
  26.                 android:layout_width="fill_parent"
  27.                 android:layout_height="wrap_content"
  28.                 />
  29.               <TextView
  30.                 android:id="@+id/text_view_font_4"
  31.                 android:layout_width="fill_parent"
  32.                 android:layout_height="wrap_content"
  33.                 />
  34.               <TextView
  35.                 android:id="@+id/text_view_font_5"
  36.                 android:layout_width="fill_parent"
  37.                 android:layout_height="wrap_content"
  38.                 />
  39.        </LinearLayout>
  40.     </ScrollView>
  41. </LinearLayout>
Source code: [java] view plaincopyprint?
  1. package com.android.effective;  
  2. import java.util.regex.Matcher;  
  3. import java.util.regex.Pattern;  
  4. import android.app.Activity;  
  5. import android.graphics.Color;  
  6. import android.graphics.Typeface;  
  7. import android.os.Bundle;  
  8. import android.text.Spannable;  
  9. import android.text.SpannableString;  
  10. import android.text.SpannableStringBuilder;  
  11. import android.text.style.AbsoluteSizeSpan;  
  12. import android.text.style.BackgroundColorSpan;  
  13. import android.text.style.ForegroundColorSpan;  
  14. import android.text.style.QuoteSpan;  
  15. import android.text.style.RelativeSizeSpan;  
  16. import android.text.style.ScaleXSpan;  
  17. import android.text.style.StrikethroughSpan;  
  18. import android.text.style.StyleSpan;  
  19. import android.text.style.TypefaceSpan;  
  20. import android.text.style.URLSpan;  
  21. import android.text.util.Linkify;  
  22. import android.widget.TextView;  
  23. publicclass TextViewFontActivity extends Activity {  
  24.     @Override
  25.     publicvoid onCreate(Bundle bundle) {  
  26.         super.onCreate(bundle);  
  27.         setContentView(R.layout.textview_font_1);  
  28.         // Demonstration of basic SpannableString and spans usage
  29.         final TextView textWithString = (TextView) findViewById(R.id.text_view_font_1);  
  30.         String w = "The quick fox jumps over the lazy dog";  
  31.         int start = w.indexOf('q');  
  32.         int end = w.indexOf('k') + 1;  
  33.         Spannable word = new SpannableString(w);  
  34.         word.setSpan(new AbsoluteSizeSpan(22), start, end,   
  35.                 Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  36.         word.setSpan(new StyleSpan(Typeface.BOLD), start, end,   
  37.                 Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  38.         word.setSpan(new BackgroundColorSpan(Color.RED), start, end,   
  39.                 Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  40.         textWithString.setText(word);  
  41.         // Demonstration of basic SpannableStringBuilder and spans usage
  42.         final TextView textWithBuilder = (TextView) findViewById(R.id.text_view_font_2);  
  43.         SpannableStringBuilder word2 = new SpannableStringBuilder();  
  44.         final String one = "Freedom is nothing but a chance to be better!";  
  45.         final String two = "The quick fox jumps over the lazy dog!";  
  46.         final String three = "The tree of liberty must be refreshed from time to time with " +  
  47.                 "the blood of patroits and tyrants!";  
  48.         word2.append(one);  
  49.         start = 0;  
  50.         end = one.length();  
  51.         word2.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  52.         word2.append(two);  
  53.         start = end;  
  54.         end += two.length();  
  55.         word2.setSpan(new ForegroundColorSpan(Color.CYAN), start, end,   
  56.                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  57.         word2.append(three);  
  58.         start = end;  
  59.         end += three.length();  
  60.         word2.setSpan(new URLSpan(three), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  61.         textWithBuilder.setText(word2);  
  62.         // Troubleshooting when using SpannableStringBuilder
  63.         final TextView textTroubles = (TextView) findViewById(R.id.text_view_font_3);  
  64.         SpannableStringBuilder word3 = new SpannableStringBuilder();  
  65.         start = 0;  
  66.         end = one.length();  
  67.         // Caution: must first append or set text to SpannableStringBuilder or SpannableString
  68.         // then set the spans to them, otherwise, IndexOutOfBoundException is thrown when setting spans
  69.         word3.append(one);  
  70.         // For AbsoluteSizeSpan, the flag must be set to 0, otherwise, it will apply this span to until end of text
  71.         word3.setSpan(new AbsoluteSizeSpan(22), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  72.         // For BackgroundColorSpanSpan, the flag must be set to 0, otherwise, it will apply this span to end of text
  73.         word3.setSpan(new BackgroundColorSpan(Color.DKGRAY), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  74.         word3.append(two);  
  75.         start = end;  
  76.         end += two.length();  
  77.         word3.setSpan(new TypefaceSpan("sans-serif"), start, end,   
  78.                 Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  79.         // TODO: sometimes, flag must be set to 0, otherwise it will apply the span to until end of text
  80.         // which MIGHT has nothing to do with specific span type.
  81.         word3.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  82.         word3.setSpan(new ScaleXSpan(0.618f), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  83.         word3.setSpan(new StrikethroughSpan(), start, end, 0);//Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  84.         word3.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  85.         word3.setSpan(new QuoteSpan(), start, end, 0); //Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  86.         word3.append(three);  
  87.         start = end;  
  88.         end += three.length();  
  89.         word3.setSpan(new RelativeSizeSpan((float) Math.E), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  90.         word3.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  91.         textTroubles.setText(word3);  
  92.         // Highlight some patterns
  93.         final String four = "The gap between the best software engineering " +  
  94.                 "practice and the average practice is very wide¡ªperhaps wider " +  
  95.                 " than in any other engineering discipline. A tool that disseminates " +  
  96.                 "good practice would be important.¡ªFred Brooks";  
  97.         final Pattern highlight = Pattern.compile("the");  
  98.         final TextView textHighlight = (TextView) findViewById(R.id.text_view_font_4);  
  99.         SpannableString word4 = new SpannableString(four);  
  100.         Matcher m = highlight.matcher(word4.toString());  
  101.         while (m.find()) {  
  102.             word4.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(),   
  103.                     Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  104.             word4.setSpan(new ForegroundColorSpan(Color.RED), m.start(), m.end(),   
  105.                     Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  106.             word4.setSpan(new StrikethroughSpan(), m.start(), m.end(),   
  107.                     Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  108.         }  
  109.         textHighlight.setText(word4);  
  110.         // Set numbers, URLs and E-mail address to be clickable with TextView#setAutoLinkMask
  111.         final TextView textClickable = (TextView) findViewById(R.id.text_view_font_5);    
  112.         final String contact = "Email: [email protected]\n" +  
  113.                 "Phone: +47-24885883\n" +  
  114.                 "Fax: +47-24885883\n" +  
  115.                 "HTTP: www.microsoft.com/mvp.asp";  
  116.         // Set the attribute first, then set the text. Otherwise, it won't work
  117.         textClickable.setAutoLinkMask(Linkify.ALL); // or set 'android:autoLink' in layout xml
  118.         textClickable.setText(contact);  
  119.     }  
  120. }  
The results:

轉自:http://blog.csdn.net/hitlion2008/article/details/6856780