/**
* 關(guān)鍵字高亮顯示
*
* @param context 上下文
* @param text 需要顯示的文字
* @param target 需要高亮的關(guān)鍵字
* @param color 高亮顏色
* @param start 頭部增加高亮文字個數(shù)
* @param end 尾部增加高亮文字個數(shù)
* @return 處理完后的結(jié)果
*/
public static SpannableString highlight(Context context, String text, String target,
String color, int start, int end) {
SpannableString spannableString = new SpannableString(text);
Pattern pattern = Pattern.compile(target);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor(color));
spannableString.setSpan(span, matcher.start() - start, matcher.end() + end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableString;
}
start與end參數(shù)默認(rèn)情況下傳0,當(dāng)需要高亮的關(guān)鍵字前后有符號時(比如[高亮])语盈,start與end參數(shù)可傳1。
調(diào)用方法
SpannableString highlightText = StringUtils.highlight(this, "關(guān)鍵字高亮", "高亮", "#EA2D2D", 0, 0);
textView.setText(highlightText);
效果如下圖所示:
文字高亮