天天看点

TextView局部文字样式美化(SpannableStringBuilder)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qingfeng812/article/details/52100710

附属图片:      
具体使用参考文章:      
http://www.cnblogs.com/hacjy/p/5124863.html
      
文字处理工具函数:      
/**
     * @desc:修改textView样式
     * @author:Arison on 2016/8/3
     */
    public static void textSpanForStyle(
            TextView view,
            String input,
            String match,
            int color) {
        SpannableStringBuilder style=new SpannableStringBuilder(input);
        Pattern highlight = Pattern.compile(match);
        Matcher m = highlight.matcher(style.toString());
        while (m.find()) {
            style.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(),
                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            style.setSpan(new ForegroundColorSpan(color), m.start(), m.end(),
                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//            style.setSpan(new StrikethroughSpan(), m.start(), m.end(), 
//                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            style.setSpan(new UnderlineSpan(), m.start(), m.end(),
                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        view.setText(style);
    }


    /**
     * @desc:修改textView样式  批量修改
     * @author:Arison on 2016/8/3
     */
    public static void textAarrySpanForStyle(
            TextView view,
            String input,
            String[] match,
            int color) {
        SpannableStringBuilder style=new SpannableStringBuilder(input);
        for (String item:match){
            Pattern highlight = Pattern.compile(item);
            Matcher m = highlight.matcher(style.toString());
            while (m.find()) {
                style.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), m.start(), m.end(),
                        Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                style.setSpan(new ForegroundColorSpan(color), m.start(), m.end(),
                        Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//            style.setSpan(new StrikethroughSpan(), m.start(), m.end(), 
//                    Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                style.setSpan(new UnderlineSpan(), m.start(), m.end(),
                        Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
        }
        view.setText(style);
        }      

继续阅读