1. 程式人生 > >Android搜尋列表關鍵詞高亮顯示

Android搜尋列表關鍵詞高亮顯示

很多App裡面都有搜尋的功能,搜尋的結果列表高亮顯示會使app體驗更好.
採用正則匹配找出字串setSpan設定顏色,當用戶輸入特殊字元時先將特殊字元進行轉義然後再進行匹配變色
話不多說,上程式碼

/**
 * 文字變色工具類
 */
public class KeywordUtil {

    /**
     * 關鍵字高亮變色
     * 
     * @param color
     *            變化的色值
     * @param text
     *            文字
     * @param keyword
     *            文字中的關鍵字
     * @return
結果SpannableString */
public static SpannableString matcherSearchTitle(int color, String text, String keyword) { SpannableString s = new SpannableString(text); keyword=escapeExprSpecialWord(keyword); text=escapeExprSpecialWord(text); if (text.contains(keyword)&&!TextUtils.isEmpty(keyword)){ try
{ 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); } }catch
(Exception e){ AppLog.e(e.toString()); } } return s; } /** * 轉義正則特殊字元 ($()*+.[]?\^{},|) * * @param keyword * @return keyword */ public static String escapeExprSpecialWord(String keyword) { if (!TextUtils.isEmpty(keyword)) { String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" }; for (String key : fbsArr) { if (keyword.contains(key)) { keyword = keyword.replace(key, "\\" + key); } } } return keyword; } }