在搜索界面需要关键字与搜索出来的文字高亮显示并且不区分字母大小写:
/** * 关键字高亮变色 * * @param color 变化的色值 * @param text 文字 * @param keyword 文字中的关键字 * @return 结果SpannableString */ public static SpannableString matcherSearchTitle(int color, String text, String keyword) { SpannableString s = new SpannableString(text.toLowerCase()); SpannableString spannableString = new SpannableString(text); keyword=escapeExprSpecialWord(keyword); text=escapeExprSpecialWord(text); if ((text.toLowerCase()).contains(keyword.toLowerCase())&&!TextUtils.isEmpty(keyword)){ try { Pattern p = Pattern.compile(keyword.toLowerCase()); Matcher m = p.matcher(s); while (m.find()) { int start = m.start(); int end = m.end(); spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } }catch (Exception e){ } } return spannableString; } /** * 转义正则特殊字符 ($()*+.[]?\^{},|) * * @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; }