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

Android TextView 關鍵字變色實作

編輯:關於 Android 程式設計

在 Android 介面中,若想讓 TextView 的部分文字以不同顏色標示,可以使用 SpannableStringBuilder 或 SpannableString。以下整理四種常見情境:固定關鍵字變色、搜尋第一個關鍵字變色、搜尋全部關鍵字變色,以及不分大小寫比對。

固定字串變色

若文字與變色位置固定,可直接計算 index,再用 ForegroundColorSpan 設定範圍:

SpannableStringBuilder style = new SpannableStringBuilder(text);
style.setSpan(new ForegroundColorSpan(color1), 0, text1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(color2), start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

搜尋關鍵字並變色

若需要找出使用者輸入的關鍵字,可先用 indexOf 找到位置,再設定顏色:

int index = string.indexOf(keyWord);
if (index != -1) {
    builder.setSpan(new ForegroundColorSpan(color), index, index + keyWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

全部關鍵字變色

若要讓所有相同關鍵字都變色,可使用 Pattern 與 Matcher 找出每一段符合的位置:

Pattern pattern = Pattern.compile(keyword);
Matcher matcher = pattern.matcher(ss);
while (matcher.find()) {
    ss.setSpan(new ForegroundColorSpan(color), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}

不分大小寫比對

若搜尋字母時希望不分大小寫,可先將原字串與關鍵字轉為小寫,再進行比對;但最終顯示仍應使用原始文字:

String string = text.toLowerCase();
String key = keyword.toLowerCase();
Pattern pattern = Pattern.compile(key);
Matcher matcher = pattern.matcher(string);

這些方法都能讓 TextView 的重點更明顯,常用於搜尋結果、提示訊息或條款標示。

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