先上效果:
代码实现:
text 数据源
keyword 要变颜色的字符串
color_FA9A3A 要变的颜色
style_color_FA9A3A 也可以改变字体的size和其他的熟悉,自己设置
public SpannableString matcherSearchText( String text, String keyword) {
SpannableString ss = new SpannableString(text);
Pattern pattern = Pattern.compile(keyword);
Matcher matcher = pattern.matcher(ss);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
ss.setSpan(new TextAppearanceSpan(this, R.style.style_color_FA9A3A), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//new ForegroundColorSpan(color)
}
return ss;
}
<style name="style_color_FA9A3A">
<item name="android:textColor">@color/color_FA9A3A</item>
</style>
<color name="color_FA9A3A">#FA9A3A</color>
补充一下怎么使用:
private TextView tvName;
tvName.setText(matcherSearchText(text, keyword));