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

后端 未结 9 1546
眼角桃花
眼角桃花 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:46

    From API 21 SpannableStringBuilder includes a simple method to do this. Here is a solution example:

    SpannableStringBuilder builder= new SpannableStringBuilder();
    StyleSpan boldSpan = new StyleSpan(android.graphics.Typeface.BOLD);
    builder.append("First Part Not Bold ")
                  .append("BOLD ", boldSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                  .append("rest not bold");
    

    Since it is a good chance you do not support API 21 only you can duplicate the code from that method:

    public SpannableStringBuilder append(CharSequence text, Object what, int flags) {
            int start = length();
            append(text);
            setSpan(what, start, length(), flags);
            return this;
    }
    

提交回复
热议问题