建立 SpannableString,對指定字元範圍套用 ForegroundColorSpan,再設定給 TextView,實現部分文字變色。
String fullText = "I know just how to whisper";
SpannableString spannable = new SpannableString(fullText);
// 從索引 5 到 13 (不含) 設為藍色:"just how"
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
start、end:字元索引範圍(0 起算,end 不包含)。flags:SPAN_EXCLUSIVE_EXCLUSIVE 表示插入文字時不擴展範圍。BackgroundColorSpan:背景色。StyleSpan:粗體/斜體。UnderlineSpan:底線。ClickableSpan:可點擊區域。ImageSpan:插入圖片。若關鍵字位置不固定,可用 fullText.indexOf(keyword) 計算 start/end。