Android中TextView的文字內容中指定關鍵字高亮顯示
阿新 • • 發佈:2019-01-03
讓TextView的文字中指定關鍵字高亮顯示的工具類
public class HighLightKeyWordUtil {
/**
* @param color 關鍵字顏色
* @param text 文字
* @param keyword 關鍵字
* @return
*/
public static SpannableString getHighLightKeyWord(int color, String text,String keyword) {
SpannableString s = new SpannableString(text);
Pattern p = Pattern.compile(keyword);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return s;
}
/**
* @param color 關鍵字顏色
* @param text 文字
* @param keyword 多個關鍵字
* @return
*/
public static SpannableString getHighLightKeyWord(int color, String text,String[] keyword) {
SpannableString s = new SpannableString(text);
for (int i = 0 ; i < keyword.length; i++) {
Pattern p = Pattern.compile(keyword[i]);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return s;
}
}