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

Code Droid picture Code Droid · May 31, 2012 · Viewed 82.1k times · Source

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.

Answer

Mohammed Azharuddin Shaikh picture Mohammed Azharuddin Shaikh · May 31, 2012
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);