有这样一个需求,搜索结果的关键字要高亮变色显示
可以通过循环遍历,根据
ForegroundColorSpan
来识别
单个关键字变色
/**
* 关键字高亮变色
*
* @param color 颜色值
* @param text 文字
* @param keyword 关键字
* @return
*/
public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
SpannableString s = new SpannableString(text);
Pattern p = Pattern.compile(keyword);
Matcher matcher = p.matcher(s);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.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[] keyword) {
SpannableString s = new SpannableString(text);
for (int i = 0; i < keyword.length; i++) {
Pattern p = Pattern.compile(keyword[i]);
Matcher matcher = p.matcher(s);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
s.setSpan(new ForegroundColorSpan(color), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return s;
}
调用:
matcherSearchTitle(this.getResources().getColor(R.color.color_4d95d3),"一个专业移动开发特效分享平台,为您提供各种移动开发最新资讯和实用知识手册,提供高价值的信息服务平台。同时提供一些优美文章,让您以轻松状态更好的学习和工作!",new String[] {"爱开发","专业","知识","。"})
效果:
正则表达式匹配有误的,请过滤处理
https://mp.weixin.qq.com/s/sKljkGN-3lOxO7KvtDJZVA