SpannableStringBuilder to create String with multiple fonts/text sizes etc Example?

后端 未结 9 1488
眼角桃花
眼角桃花 2020-11-28 03:00

I need to create a String placed in a TextView that will display a string like this:

First Part Not Bold BOLD rest not bold

9条回答
  •  清酒与你
    2020-11-28 03:48

    This code should set to bold everything that comes inside the html bold tag. And it also deletes the tag so only the content inside is displayed.

            SpannableStringBuilder sb = new SpannableStringBuilder("this is bold and this is bold too  and this is bold too, again.");
    
            Pattern p = Pattern.compile(".*?", Pattern.CASE_INSENSITIVE);            
            boolean stop = false;
            while (!stop)
            {
                Matcher m = p.matcher(sb.toString());
                if (m.find()) {
                    sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    sb.delete(m.end()-4, m.end());
                    sb.delete(m.start(), m.start() + 3);
                }
                else
                    stop = true;
            }
    

    This code can also be adapted for other html style tags, such as Superscript (sup tag), etc.

            SpannableStringBuilder sb = new SpannableStringBuilder("text has superscript tag");
    
            Pattern p = Pattern.compile(".*?", Pattern.CASE_INSENSITIVE);            
            boolean stop = false;
            while (!stop)
            {
                Matcher m = p.matcher(sb.toString());
                if (m.find()) {
                    sb.setSpan(new SuperscriptSpan(), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    sb.delete(m.end()-6, m.end());
                    sb.delete(m.start(), m.start() + 5);
                }
                else
                    stop = true;
            }
    

    To set the color, just use the ForegroundColorSpan with setSpan.

    sb.setSpan(new ForegroundColorSpan(Color.rgb(255, 0, 0)), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    

    Hope it helps.

提交回复
热议问题