androidspannablestringspannablestringbuilder

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


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

So I want to know how I could use SpannableStringBuilder to do this?

I could use three TextEdit to accomplish this but I would like to use best solution.


Solution

  • First Part Not Bold   BOLD  rest not bold
    

    You can do this either as @Rajesh suggested or by this.

    String normalBefore= "First Part Not Bold ";
    String normalBOLD=  "BOLD ";
    String normalAfter= "rest not bold";
    String finalString= normalBefore+normalBOLD+normalAfter;
    Spannable sb = new SpannableString( finalString );
    sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), finalString.indexOf(normalBOLD)+ normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bold
    sb.setSpan(new AbsoluteSizeSpan(intSize), finalString.indexOf(normalBOLD)+ normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//resize size
    

    to show this in TextView

    textview.setText(sb,  TextView.BufferType.SPANNABLE);