編輯:關於 Android 程式設計
在開發應用時,經常需要顯示帶有不同字型風格的資訊,就像預設鎖定畫面上那樣,時間與充電資訊往往各有各的樣式。遇到類似需求,直覺反應可能是用多個 TextView 分別設定不同字型來拼湊。下圖就是一個例子:

不過這裡更推薦的做法,是運用 android.text.* 與 android.text.style.* 底下的元件來實作 Rich Text,也就是在同一個 TextView 中設定不同的字型風格。對於文本編輯、記事本、簡訊、多媒體簡訊這類應用而言,幾乎非得使用這些元件,才能達到理想的顯示效果。
主要的核心工具類別有 android.text.Spanned、android.text.SpannableString 與 android.text.SpannableStringBuilder,它們用來取代一般的 String。SpannableString 與 SpannableStringBuilder 可以設定不同的 Span,而這些 Span 正是實現 Rich Text 的關鍵,例如粗體、斜體、前景色、背景色、字型大小、字型風格等,android.text.style.* 中定義了琳瑯滿目的 Span 類型供開發者選用。
相關 API 的類別階層如下:

由於 Spannable 系列最終都實作了 CharSequence 介面,因此可以透過 TextView.setText() 直接把 SpannableString 或 SpannableStringBuilder 設定給 TextView。
當要顯示 Rich Text 時,可以建立一個 SpannableString 或 SpannableStringBuilder。兩者的差異在於:SpannableString 比較像 String,在建立物件時傳入一個 String,之後便無法再更改內容,也無法拼接多個 SpannableString;而 SpannableStringBuilder 則更像 StringBuilder,可以透過 append() 方法拼接多個字串:
SpannableString word = new SpannableString("The quick fox jumps over the lazy dog");
SpannableStringBuilder multiWord = new SpannableStringBuilder();
multiWord.append("The Quick Fox");
multiWord.append("jumps over");
multiWord.append("the lazy dog");
建立好 Spannable 物件後,就能為它們設定 Span 來實現想要的 Rich Text。常見的 Span 有:
• AbsoluteSizeSpan(int size) —— 設定字型大小,參數為絕對數值,相當於 Word 中的字級設定。
• RelativeSizeSpan(float proportion) —— 設定字型大小,參數是相對於預設字型的倍數。若預設字型為 x,設定後即為 x × proportion,使用起來更靈活:proportion > 1 為放大,< 1 為縮小。
• ScaleXSpan(float proportion) —— 縮放字型,預設為 1,設定後為原值乘以 proportion,大於 1 放大、小於 1 縮小。
• 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 —— 設定此風格後,會有一條線從文字中央劃過,就像被刪除一樣。
使用這些 Style span 時,通常只需傳入上述的建構參數即可,無需額外設定其他屬性;若有需要,也可以對它們設定其他屬性,詳情可參考官方文件。
SpannableString 與 SpannableStringBuilder 都具備以下設定 Span 的方法:
/** * Set the style span to Spannable, such as SpannableString or SpannableStringBuilder * @param what --- the style span, such as StyleSpan * @param start --- the starting index of characters to which the style span to apply * @param end --- the ending index of characters to which the style span to apply * @param flags --- the flag specified to control */ setSpan(Object what, int start, int end, int flags);
其中 what 是要設定的 Style span,start 與 end 標示 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 一路套用到文字結尾,而非僅限於 start 與 end 之間,這時就需要改用 Flag 0。
另外,也可以透過 TextView.setAutoLink(int) 設定 Linkify 屬性。它的作用在於,TextView 會自動檢查內容,辨識出電話號碼、網址或電子郵件,並標示為可點擊的超連結,點擊後便會跳轉到對應應用,如撥號程式、瀏覽器或郵件。Linkify 有幾個常用選項,更多請參考官方文件:
• Linkify.EMAIL_ADDRESS —— 僅辨識 Email 位址並標示為超連結,點擊後跳轉到郵件程式。
• Linkify.PHONE_NUMBERS —— 僅辨識電話號碼,點擊後跳轉到撥號程式並撥打該號碼。
• Linkify.WEB_URLS —— 僅辨識網址,點擊後跳轉到瀏覽器開啟該 URL。
• Linkify.ALL —— 辨識所有系統支援的特殊 Uri,並執行相應操作。
個人認為,軟體開發中最常見的問題往往不是「某個技巧怎麼用」,而是「何時該用哪個技巧」。因為達成同一目標可能有 N 種方法,就必須權衡利弊、挑選最合適的一個。正如常言所云:沒有最好的,只有最適合的。
以呈現不同字型的資訊為例,除了 Style Span,也可以採用多個 TextView。那麼該如何權衡呢?以下是我的幾點心得:
1. 若顯示的是多個不同類別的資訊,應使用多個 TextView,這樣也方便各自控制與變更。例如預設鎖定畫面上的日期與充電資訊,因為承載的內容不同,就適合用多個 TextView 分別呈現。
2. 若顯示的是同一類或同一則資訊,則應使用 StyleSpan。例如簡訊中要突顯聯絡人的相關資訊,或想 Highlight 某些關鍵字時。
3. 若要實現真正的 Rich Text,那就別無選擇,只能使用 Style span。
4. 若要實現某些特殊視覺效果,也可以考慮 StyleSpan。設定不同字型風格只是初階應用,深入研究後會發現它有許多奧妙之處。
版面配置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/text_view_font_1"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/text_view_font_2"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/text_view_font_3"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/text_view_font_4"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/text_view_font_5"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</LinearLayout>
程式碼:
package com.android.effective;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.QuoteSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.ScaleXSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.widget.TextView;
public class TextViewFontActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.textview_font_1);
// Demonstration of basic SpannableString and spans usage
final TextView 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 = new SpannableString(w);
word.setSpan(new AbsoluteSizeSpan(22), start, end,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word.setSpan(new StyleSpan(Typeface.BOLD), start, end,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word.setSpan(new BackgroundColorSpan(Color.RED), start, end,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textWithString.setText(word);
// Demonstration of basic SpannableStringBuilder and spans usage
final TextView textWithBuilder = (TextView) findViewById(R.id.text_view_font_2);
SpannableStringBuilder word2 = new SpannableStringBuilder();
final String one = "Freedom is nothing but a chance to be better!";
final String two = "The quick fox jumps over the lazy dog!";
final String three = "The tree of liberty must be refreshed from time to time with "
+ "the blood of patroits and tyrants!";
word2.append(one);
start = 0;
end = one.length();
word2.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
word2.append(two);
start = end;
end += two.length();
word2.setSpan(new ForegroundColorSpan(Color.CYAN), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
word2.append(three);
start = end;
end += three.length();
word2.setSpan(new URLSpan(three), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textWithBuilder.setText(word2);
// Troubleshooting when using SpannableStringBuilder
final TextView textTroubles = (TextView) findViewById(R.id.text_view_font_3);
SpannableStringBuilder word3 = new SpannableStringBuilder();
start = 0;
end = one.length();
// Caution: must first append or set text to SpannableStringBuilder or SpannableString
// then set the spans to them, otherwise, IndexOutOfBoundException is thrown when setting spans
word3.append(one);
// For AbsoluteSizeSpan, the flag must be set to 0, otherwise it will apply to end of text
word3.setSpan(new AbsoluteSizeSpan(22), start, end, 0);
// For BackgroundColorSpan, the flag must be set to 0, otherwise it will apply to end of text
word3.setSpan(new BackgroundColorSpan(Color.DKGRAY), start, end, 0);
word3.append(two);
start = end;
end += two.length();
word3.setSpan(new TypefaceSpan("sans-serif"), start, end,
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word3.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), start, end, 0);
word3.setSpan(new ScaleXSpan(0.618f), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word3.setSpan(new StrikethroughSpan(), start, end, 0);
word3.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word3.setSpan(new QuoteSpan(), start, end, 0);
word3.append(three);
start = end;
end += three.length();
word3.setSpan(new RelativeSizeSpan((float) Math.E), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word3.setSpan(new ForegroundColorSpan(Color.BLUE), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textTroubles.setText(word3);
// Highlight some patterns
final String four = "The gap between the best software engineering "
+ "practice and the average practice is very wide—perhaps wider "
+ " than in any other engineering discipline. A tool that disseminates "
+ "good practice would be important.—Fred Brooks";
final Pattern highlight = Pattern.compile("the");
final TextView textHighlight = (TextView) findViewById(R.id.text_view_font_4);
SpannableString word4 = new SpannableString(four);
Matcher m = highlight.matcher(word4.toString());
while (m.find()) {
word4.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word4.setSpan(new ForegroundColorSpan(Color.RED), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
word4.setSpan(new StrikethroughSpan(), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
textHighlight.setText(word4);
// Set numbers, URLs and E-mail address to be clickable
final TextView textClickable = (TextView) findViewById(R.id.text_view_font_5);
final String contact = "Email: mvp@microsoft.com\n"
+ "Phone: +47-24885883\n"
+ "Fax: +47-24885883\n"
+ "HTTP: www.microsoft.com/mvp.asp";
// Set the attribute first, then set the text. Otherwise, it won't work
textClickable.setAutoLinkMask(Linkify.ALL); // or set 'android:autoLink' in layout xml
textClickable.setText(contact);
}
}
執行結果:


Android 學習之路:從非 Java 工程師視角理解系統架構與專案結構
從非 Java 工程師的視角開始 這是「Android 學習之路」系列的第一篇。本文先不急著實作簡易版微信,而是把學習起點、對 Android 的理解,以及 Androi
Android 程式如何判斷手機是否已取得 Root 權限
有些功能非得要 root 才能動,例如自動安裝、系統層級的檔案操作等等。既然功能依賴 root,那在呼叫之前就得先確認環境是否具備條件,否則只會拿到一堆例外。以下整理幾種
軟鍵盤與版面配置:windowSoftInputMode 設定完整指南
輸入法彈出時把輸入框蓋住、頁面卻沒有跟著上移,是 Android 開發中最常見的畫面錯位問題之一。最簡潔的解法是在 AndroidManifest.xml 中,為對應的
Fresco:Facebook 開源的 Android 圖片加載框架深度解析
在 Android 裝置上,快速而高效地顯示圖片是至關重要的一環。過去幾年,我們在圖片記憶體管理上踩過不少坑:圖片尺寸龐大,手機記憶體卻相當有限。每一個像素的 R、G、B