欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

安卓实现高亮显示文字中的某段文字

程序员文章站 2023-12-24 19:04:21
...

1.高亮显示文字中的某段文字

public static void lightShow(String content, String lightContent, TextView textView) {
        SpannableString spannableString = new SpannableString(content);
        Pattern p = Pattern.compile(lightContent);
        Matcher m = p.matcher(content);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            spannableString.setSpan(new ForegroundColorSpan(BaseApplication.getCurrentActivity().getResources().getColor(R.color.font_5e8)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textView.setText(spannableString);
    }

2.高亮显示文字中的某2段文字并且带下划线的

 public static void lightAndLineShow2(String content, String lightContent,String lightContent2, TextView textView) {
        SpannableString spannableString = new SpannableString(content);
        Pattern p = Pattern.compile(lightContent);
        Matcher m = p.matcher(content);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            spannableString.setSpan(new ForegroundColorSpan(BaseApplication.getCurrentActivity().getResources().getColor(R.color.font_5e8)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        Pattern p2 = Pattern.compile(lightContent2);
        Matcher m2 = p2.matcher(content);
        while (m2.find()) {
            int start2 = m2.start();
            int end2 = m2.end();
            spannableString.setSpan(new ForegroundColorSpan(BaseApplication.getCurrentActivity().getResources().getColor(R.color.font_5e8)), start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new UnderlineSpan(), start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textView.setText(spannableString);
    }

上一篇:

下一篇: