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

Android 自訂控制項:讓 TextView 中的關鍵字元串高亮顯示

編輯:關於 Android 程式設計

需求是這樣的

假設你手上有一串文字 123456789,產品只要求把中間的 345 標成另一個顏色,其餘維持原樣。這種「局部高亮」該怎麼做?

新手常見的第一反應是把字元切成好幾段,各自塞進不同的 TextView,再逐個上色。聽起來可行,但維護成本極高,光是換行與對齊就夠折磨人。稍有經驗的開發者則會直接想到 Android 已經幫我們封裝好的 SpannableStringBuilder——它能對同一段文字裡的特定範圍套用樣式,正是為此而生。

接下來我們就沿用 Android 既有的封裝思路,做出一個自己的 LightTextView,讓它同時支援在 XML 與 Java 程式碼中設定。

效果預覽

範例裡放了兩個 LightTextView:一個比對所有電子郵件格式,另一個比對所有數字。細節可以參考文末的範例。

功能清單

1. 設定文字內容
2. 設定要比對的正則表達式
3. 設定比對成功子字串的前景色
4. 設定比對成功子字串的底色
5. 選擇是否套用前景色
6. 選擇是否套用底色
7. 一次套用以上所有設定

做法一:用 Java 程式碼設定屬性

純 Java 設定屬性其實很直覺,只要對外開放一組 setter 即可:

/** 設定底色 */
private int mBackColor;
public void setBackColor(int color) {
    mBackColor = color;
}

相比 XML 的 attrs 宣告,Java 這邊確實省事。不過真正撐起功能的核心邏輯,仍然要靠 Java:

private void showForeBackground() {
    SpannableStringBuilder styleBuilder = new SpannableStringBuilder(mText);
    // 包裝文字內容
    if (mDecbackground) {
        for (int i = 0; i < matchedText.size(); i++) {
            styleBuilder.setSpan(new BackgroundColorSpan(mBackColor),
                    matchedText.get(i).getStart(), matchedText.get(i).getEnd(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    if (mDecForeground) {
        for (int i = 0; i < matchedText.size(); i++) {
            styleBuilder.setSpan(new ForegroundColorSpan(mForeColor),
                    matchedText.get(i).getStart(), matchedText.get(i).getEnd(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    setText(styleBuilder);
}

這段程式在做的事,就是替所有比對到的區間掛上樣式。其中要注意 matchedText:

private List<SubMatchModel> matchedText = null;

它是一個 List,因為一段文字裡可能有多個符合條件的子字串。而 SubMatchModel 是我們自己定義的資料模型,用來記錄每一次比對的結果:

public class SubMatchModel {
    private String subString;   // 比對到的子字串
    private int start;          // 起始位置
    private int end;            // 結束位置

    public String getSubString() { return subString; }
    public void setSubString(String subString) { this.subString = subString; }
    public int getStart() { return start; }
    public void setStart(int start) { this.start = start; }
    public int getEnd() { return end; }
    public void setEnd(int end) { this.end = end; }
}

接著就是比對本身。用 Pattern 編譯正則,再用 Matcher 逐一找出符合的片段,把位置資訊存進 List:

/** 取得字串中所有符合正則的子字串 */
public static List<SubMatchModel> getMatchString(String str, String exp) {
    Pattern p = Pattern.compile(exp);
    Matcher m = p.matcher(str);
    List<SubMatchModel> models = new ArrayList<SubMatchModel>();
    SubMatchModel model = null;
    while (m.find()) {
        model = new SubMatchModel();
        model.setSubString(m.group());
        model.setStart(m.start());
        model.setEnd(m.end());
        models.add(model);
    }
    return models;
}

使用示範

private LightTextView mShowLightTextView = null;

private void resetWidgets() {
    mShowLightTextView.setIsMatchOrNot(true);
    mShowLightTextView.setText("我的郵箱地址是:abcdef@126.com,你的郵箱地址是:123548@qq.com");
    mShowLightTextView.setRegularExp(Utils.getMatchEmailString());
    mShowLightTextView.setBackColor(Color.BLUE);
    mShowLightTextView.setForeColor(Color.RED);
    mShowLightTextView.setDecbackground(true);
    mShowLightTextView.setDecForeground(true);
    mShowLightTextView.show();
}

最後那個 show() 不是用來顯示控制項的,它只是把前面累積的一堆設定一次套用上去而已,命名上容易誤會,用時心裡有數就好。

做法二:改用自訂屬性 attrs

看完上面的設定流程,你大概會覺得步驟有點繁瑣。這和前面說「Java 比較簡單」並不矛盾——兩者講的是不同角度。程式寫得省事,呼叫端就複雜;呼叫端寫得乾淨,內部邏輯就得吃掉複雜度。這就是得失平衡。

attrs 的宣告本身很樸素:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="LightTextView">
    </declare-styleable>
</resources>

幾個要留意的細節

1. 在 Java 的建構子中讀取屬性:

private void init(TypedArray array) {
    mText = array.getString(R.styleable.LightTextView_text);
    mIsMatch = array.getBoolean(R.styleable.LightTextView_isMatch, true);
    mDecForeground = array.getBoolean(R.styleable.LightTextView_decForeground, false);
    mDecbackground = array.getBoolean(R.styleable.LightTextView_decbackground, false);
    mForeColor = array.getColor(R.styleable.LightTextView_foregroundColor, Color.BLACK);
    mBackColor = array.getColor(R.styleable.LightTextView_backgroundColor, Color.WHITE);
}

並在建構子中呼叫:

public LightTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.LightTextView);
    init(mTypedArray);
}

2. XML 中必須帶上自訂屬性的命名空間,也就是 xmlns 那一行。

圖中被框出的兩處要特別小心:前者是你宣告的自訂屬性名稱,後者則必須是應用程式本身的套件名稱,而不是自訂控制項所在的套件。這一步填錯,屬性就會讀不到。

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