android 字符串特定字符变色

先上效果:
在这里插入图片描述

代码实现:
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));
发布了40 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/CGG92/article/details/95335832