Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TextView 進階用法:圖文並茂、可點擊文字與自訂樣式 Span

編輯:關於 Android 程式設計

我們平常使用 TextView,多半只把它當成一個顯示文字的容器,但它的能力遠不止於此。本文整理幾個實務上非常實用的進階技巧。

先談談 Android 設定文字樣式的幾種途徑:

1. 把 android:autoLink 設為 true,系統會自動識別 E-mail、電話、網址等特殊文本。

2. 使用 HTML 標籤,例如 <font>、<img> 等,此時不要設定 autoLink。

3. 在 Java 程式碼中直接用 Span 物件設定樣式,需先把文字轉成 SpannableString 或 SpannableStringBuilder,再呼叫 setSpan()。

4. 在字串資源中使用標籤(只支援有限幾種)設定可點擊連結,同樣不要開 autoLink。

還有一個共通前提:以上做法只要涉及「點擊動作」,就必須呼叫 TextView.setMovementMethod() 設定對應的 MovementMethod 物件,否則連結看起來是藍色的,卻怎麼點都沒反應。

一、在 TextView 中顯示圖片

瀏覽網頁時那些圖文並茂的文章,大多是從資料庫取出後直接輸出 HTML,由瀏覽器解析 <img> 的 src 並抓取圖片顯示。

但在 Android 中,事情沒那麼自動。系統解析 HTML 標籤的能力遠不及瀏覽器,它不會依 src 屬性自己去抓圖——src 指向的到底是網路網址、本地資源還是 Content URI,只有開發者自己知道,所以必須由開發者告訴系統怎麼處理。這正是 ImageGetter 介面存在的意義,而 Html.fromHtml() 讓整個流程變得相當簡單。

txtShow = (TextView) findViewById(R.id.txtShow);

String htmlText = "小黃人1號:<img src="xiaohuangren1" />"
        + "小黃人2號:<img src="xiaohuangren2" />"
        + "小黃人3號:<img src="xiaohuangren3" />";

txtShow.setText(getSpanned(htmlText));
/**
 * 將 Html 解析成樣式文本
 * @return Spanned
 */
private Spanned getSpanned(String htmlText) {
    Spanned spanned = Html.fromHtml(htmlText, new ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            // 載入圖像資源
            Drawable drawable = getResources().getDrawable(getResourceId(source));
            if (source.equals("xiaohuangren1")) {
                drawable.setBounds(0, 0, 56, 56);          // 指定縮放尺寸
            } else if (source.equals("xiaohuangren2")) {
                drawable.setBounds(0, 0, 36, 36);
            } else if (source.equals("xiaohuangren3")) {
                // 縮放到原尺寸的 75%
                drawable.setBounds(0, 0,
                        (int) (drawable.getIntrinsicWidth() * 0.75),
                        (int) (drawable.getIntrinsicHeight() * 0.75));
            }
            return drawable;
        }
    }, null);
    return spanned;
}

/**
 * 利用反射從 R.drawable 中依資源名稱取得 ID
 * @param name 圖像資源名
 * @return 圖像資源 ID
 */
protected int getResourceId(String name) {
    try {
        Field field = R.drawable.class.getField(name);
        return Integer.parseInt(field.get(null).toString());
    } catch (Exception e) {
        return 0;
    }
}

這裡有個關鍵細節:setBounds() 一定要呼叫。ImageGetter 回傳的 Drawable 若沒有設定邊界,圖片在 TextView 中會完全看不到,這是初學時最常踩的坑。另外用反射從檔名換 ID 的做法雖然靈活,但每次呼叫都有效能成本,實務上改用 getResources().getIdentifier() 會更合適。

二、點擊 TextView 中的文字開啟指定 Activity

TextView 雖然能自動識別網址、電話與 E-mail,並在點擊時觸發對應動作,但如果我們想讓點擊連結去開啟自己的 Activity 或 Service 呢?

系統內建的識別行為,其實就是在 ClickableSpan 的 onClick() 裡透過 Action 呼叫相應元件。我們照著同樣的思路,自己實作 onClick 即可。

/**
 * 點擊 TextView 中的內容啟動指定元件
 */
private void launchComponentByTextView() {
    txtLink = (TextView) findViewById(R.id.txtLink);
    String str = "單擊我啟動一個Activity";

    // 轉成 SpannableString
    SpannableString spannableString = new SpannableString(str);

    // 將整段文字設為 ClickableSpan,並實作 onClick
    spannableString.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    }, 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    txtLink.setText(spannableString);
    // 凡是點擊連結要執行的動作,都必須設定 MovementMethod
    txtLink.setMovementMethod(LinkMovementMethod.getInstance());
}

關於 setSpan() 的第四個參數,這裡用了 SPAN_EXCLUSIVE_EXCLUSIVE。這個旗標在 TextView 上差異不大,但在 EditText 上很重要:它表示在該 Span 效果的前後輸入新字元時,不會套用這個 Span 的樣式。

三、為指定文字加上顏色與背景色

歸納前面幾個例子,要設定字串中某個子字串的樣式,流程固定是五步:

(1) 把字串轉成 SpannableString 或 SpannableStringBuilder。

(2) 計算子字串的起始位置 start 與結束位置 end。

(3) 建立一個 Span 物件(android.text.style 套件中所有 XxxSpan 類別統稱)。

(4) 呼叫 setSpan 把該區間轉換為對應的 Span。

(5) 用處理完的 Spannable 物件設定給 TextView、EditText 或 Button。

SDK 的 android.text.style 套件提供了許多現成的 Span,例如 BackgroundColorSpan 就是設定背景色的常用類別:

txtSetBackgroundColor = (TextView) findViewById(R.id.txtSetBackgroundColor);
String str = "沒有背景|黃色背景";

// 第一步:轉成 SpannableString
SpannableString spannableString = new SpannableString(str);

// 第二步:計算 start 與 end
String subStr = "黃色背景";
int start = str.indexOf(subStr);
int end = start + subStr.length();

// 第三步:建立 BackgroundColorSpan
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.YELLOW);

// 第四步:套用 Span
spannableString.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// 第五步:設定給 TextView
txtSetBackgroundColor.setText(spannableString);

問題是 BackgroundColorSpan 只能設背景色,ForegroundColorSpan 只能設文字色,SDK 並沒有提供一個能同時設定兩者的 Span。這時候就自己寫一個——只要單純改樣式、不需要處理點擊動作,那麼繼承 CharacterStyle 就足夠了(ClickableSpan 本身也是 CharacterStyle 的子類,但那是因為它需要處理連結)。

/**
 * 自定義 CharacterStyle 子類,同時修改文字顏色與背景色
 */
public class ColorSpan extends CharacterStyle {
    private int textColor, backgroundColor;

    public ColorSpan(int textColor, int backgroundColor) {
        this.textColor = textColor;
        this.backgroundColor = backgroundColor;
    }

    // 覆寫 updateDrawState,在系統繪製前修改繪製屬性
    @Override
    public void updateDrawState(TextPaint tp) {
        tp.bgColor = backgroundColor;
        tp.setColor(textColor);
    }
}

updateDrawState() 會在系統開始繪製該段文字之前呼叫,用來修改繪製屬性。參數 TextPaint 是 Paint 的子類別,而 Paint 描述的正是繪製的屬性——畫筆顏色、粗細等等。

同時使用兩種 Span 的寫法如下:

txtMyColor = (TextView) findViewById(R.id.txtMyColor);
String str = "紅色字體|灰色背景";
String subStr = "灰色背景";
int start = str.indexOf(subStr);
int end = start + subStr.length();

SpannableString spannableString = new SpannableString(str);

// 前半段:紅字白底
ColorSpan colorSpan = new ColorSpan(Color.RED, Color.WHITE);
spannableString.setSpan(colorSpan, 0, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// 後半段:白字灰底
colorSpan = new ColorSpan(Color.WHITE, Color.GRAY);
spannableString.setSpan(colorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

txtMyColor.setText(spannableString);

把這套 Span 機制用熟之後,諸如「關鍵字高亮」、「閱讀條款時局部可點」、「聊天訊息中的 @提及 上色」這類需求,都能用相當乾淨的方式完成,不必再回頭去堆疊一堆自訂 View。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved