首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android TextView 關鍵字變色實作:SpannableString 完整指南

     編輯:程式設計疑難解答

需求:「我昨天已給你發郵件」——讓「昨天」顯示紅色。Android 原生 TextView 單一顏色無法滿足,核心方案是 SpannableString 配合 ForegroundColorSpan。

核心代碼(Kotlin/Java 通用)

// Java
TextView tv = findViewById(R.id.textView);
String full = "我昨天已給你發郵件";
SpannableString spannable = new SpannableString(full);
// 關鍵字 "昨天" 起始索引 1,結束索引 3 (不含)
spannable.setSpan(new ForegroundColorSpan(Color.RED), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(spannable);

// Kotlin 擴展函數一行搞定
fun TextView.highlight(keyword: String, @ColorInt color: Int) {
    val text = this.text.toString()
    val start = text.indexOf(keyword)
    if (start >= 0) {
        val spannable = SpannableString(text)
        spannable.setSpan(ForegroundColorSpan(color), start, start + keyword.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        this.text = spannable
    }
}
// 呼叫:tv.highlight("昨天", Color.RED)

多關鍵字高亮擴展

fun TextView.highlightAll(keywords: List, @ColorInt color: Int) {
    val text = this.text.toString()
    val spannable = SpannableString(text)
    keywords.forEach { kw ->
        var index = text.indexOf(kw)
        while (index >= 0) {
            spannable.setSpan(ForegroundColorSpan(color), index, index + kw.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            index = text.indexOf(kw, index + kw.length)
        }
    }
    this.text = spannable
}

進階 Span 類型

Span 類別效果典型場景
ForegroundColorSpan文字顏色關鍵字高亮
BackgroundColorSpan背景色搜尋結果標記
StyleSpan粗體/斜體強調標題
UnderlineSpan底線連結樣式
ClickableSpan可點擊+自定義事件@提及、#話題

避坑指南

  • setText(CharSequence) 而非 setText(String),否則 Span 會丟失。
  • 動態文字(如網路請求回傳)需在 UI 執行緒 runOnUiThread 中設定 Span。
  • HTML 字串替代方案:Html.fromHtml("昨天")(API 24+ 需 FROM_HTML_MODE_LEGACY),但 Span 更靈活、效能更好。
掌握 SpannableString + 各種 Span 組合,即可實現富文本編輯器級別的 TextView 顯示效果,是 Android UI 開發必備技能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved