Android匹配字符串高亮并设置点击事件

public class TextRichUtil {
    public interface RichClickLisentner {
        void onClick();
    }

    /**
     * 获取高亮字符串
     * @param content  内容
     * @param target   高亮的部分
     * @param color    高亮的颜色
     */
    public static SpannableStringBuilder getRichText(String content, String target, int color){
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
        Matcher matcher = Pattern.compile(target).matcher(content);
        while (matcher.find()){
            int start = matcher.start();
            int end = matcher.end();
            stringBuilder.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return stringBuilder;
    }

    /**
     * 设置高亮字符串
     * @param textView 控件
     * @param content  内容
     * @param target   高亮的部分
     * @param color    高亮的颜色
     * @param lisenter 高亮部分点击事件
     */
    public static void setRichText(TextView textView, String content, String target, int color, RichClickLisentner lisenter){
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
        Matcher matcher = Pattern.compile(target).matcher(content);
        while (matcher.find()){
            int start = matcher.start();
            int end = matcher.end();
            stringBuilder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View view) {
                    lisenter.onClick();
                }

                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                    ds.setColor(color);
                }
            }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textView.setText(stringBuilder);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

你可能感兴趣的:(Android匹配字符串高亮并设置点击事件)