溫馨提示×

android怎么實現文本代碼高亮

小億
166
2023-08-15 22:46:59
欄目: 編程語言

要在Android中實現文本代碼高亮,可以使用Spannable類和ForegroundColorSpan類來實現。下面是一個簡單的示例代碼:

public void highlightText(TextView textView, String text) {
// 創(chuàng)建一個Spannable對象
Spannable spannable = new SpannableString(text);
// 定義關鍵字的顏色
ForegroundColorSpan keywordColor = new ForegroundColorSpan(Color.BLUE);
// 設置需要高亮的關鍵字
String keyword = "關鍵字";
int start = text.indexOf(keyword);
int end = start + keyword.length();
// 將關鍵字的文本設置為高亮顏色
spannable.setSpan(keywordColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// 設置TextView的文本
textView.setText(spannable);
}

在上面的代碼中,我們首先創(chuàng)建一個Spannable對象來存儲需要高亮的文本。然后,我們創(chuàng)建一個ForegroundColorSpan對象來定義高亮的顏色(這里使用藍色)。接下來,我們使用indexOf方法找到關鍵字在文本中的起始位置和結束位置,并使用setSpan方法將關鍵字的文本設置為高亮顏色。最后,我們使用setText方法將Spannable對象設置給TextView。

你可以根據自己的需求修改關鍵字和高亮顏色,并調用highlightText方法來實現文本代碼高亮。

0