TextView关键字高亮

//通过正则匹配出关键字,然后使用span使之变色高亮
private SpannableString getHighLightSs(String text, String keyword, int color) {
SpannableString span = new SpannableString(text);
Pattern pattern = Pattern.compile(keyword);
Matcher matcher = pattern.matcher(span);
while (matcher.find()) {
span.setSpan(new ForegroundColorSpan(color), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return span;
}

TextView tv = findViewById(R.id.tv);
tv.setText(getHighLightSs(text,keyword,R.color.red));
posted @ 2017-11-21 11:29  yongfengnice  阅读(334)  评论(0编辑  收藏  举报