How to set BOLD,ITALIC & UNDERLINE properties to dynamic textview in Android

Below is the code sample for setting BOLD,ITALIC & UNDERLINE properties to the TextView which is dynamically created and so is the its content. We use "SpannableString" to serve this purpose.



TextView textView=(TextView)findViewById(R.id.textview);

SpannableString spannableString=new SpannableString("Hello String"/*YOUR STRING*/);
         
/*Set your desired span...*/
spannableString.setSpan(
new StyleSpan(android.graphics.Typeface.BOLD)/*OBJECT*/
          , 0/*STARTING POSITION*/
          , spannableString.length()/*ENDING POSITION*/
          , 0/*FLAGS*/);
         
/*---  Object can be any of the following  ---
new StyleSpan(android.graphics.Typeface.BOLD);
new StyleSpan(android.graphics.Typeface.ITALIC);
new StyleSpan(android.graphics.Typeface.BOLD_ITALIC);
new UnderlineSpan();
--------------------------------------------*/
    
/*   Set spanned string to views(TextView/Button..) just like
 *   any other string
 */          
textView.setText(spannableString);



Happy coding:-)

2 comments:

  1. Thanks buddy ... it helped :-)

    ReplyDelete
  2. Note that this only works for system fonts. As I learned the hard way. ;)

    ReplyDelete