通过正则 匹配 keywords
匹配之前 先 替换特殊字符
/** * 替换 正则 特殊字符 * @param keyword * @return */ private 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; } 这个时候有两种需求 : 1:如果是 需要完全匹配 才高亮 比如 keywords=“12345” 搜索结果 是"12312345678" 的话 只有 中间的 “12345” 高亮 2: 如果是 单个字符 包含就高亮 的话 就是:keywords=“12345” 搜索结果 是"12312345678" "12312345" 都高亮
针对第一种需求的话 :
/** * 关键字高亮变色 * * @param color 变化的色值 * @param text 文字 * @param keyword 文字中的关键字 * @return */ public static SpannableString matcherSearchTitles(int color, String text, String keyword) { SpannableString s = new SpannableString(text); if (StringUtils.isNotEmpty(keyword)) { 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 matcherSearchTitle(int color, String text, String keywordStr) { if(TextUtils.isEmpty(keywordStr)){ if(!TextUtils.isEmpty(text)){ return new SpannableString(text); }else{ return new SpannableString(" "); } } char[] keyword=keywordStr.toCharArray();// SpannableString spannableString = new SpannableString(text); for (int i = 0; i < keyword.length; i++) { if(text.contains(keyword[i]+"")&&!TextUtils.isEmpty(keyword[i]+"")){ try { Pattern p = Pattern.compile(escapeExprSpecialWord(keyword[i]+"")); Matcher m = p.matcher(text); while (m.find()) { int start = m.start(); int end = m.end(); spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } catch (PatternSyntaxException e) { e.printStackTrace(); } } } return spannableString; }