Android 高亮显示文本中的关键字

时间:2021-10-13 06:23:05

总结:SpannableString用好,可以各种替换Span来操作各种内容

1、文本关键字高亮关键在于:SpannableString使用

主要就是通过关键字在文本的开始index,结束index来定位到位置,设置该范围的字体颜色。

 SpannableString ssLight = new SpannableString(文本字符串);
ssPM.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.white)), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ssPM.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), 8, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv_light.setText(ssLight);

2、如何定位到关键字在文本的index:正则表达式

主要就是通过正则表达式find:找到关键字在文本的开始index,结束index

 SpannableString ssLight = new SpannableString(文本字符串);
Pattern p = Pattern.compile(关键字字符串);
Matcher m = p.matcher(s);
while (m.find()) {
int startIndex = m.start();
int endIndex = m.end();
ssLight.setSpan(new ForegroundColorSpan(getResource.getColor(R.color.white)), startIndex, endIndex,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv_light.setText(ssLight);

3、想匹配多个,就用以上方法,用关键字数组,自己抽取出一个方法进行设置。