Search code examples
androidtextviewstring-formatting

How do I set different font sizes to a string (that is highlighted, underlined) in a textview


I am displaying text in a textview without using toString(), to keep the formatting(bold, underline, italics) within the text. But now I want to set different font sizes to _etheadertext ,_etheadertext3 etc..

String header = _etheadertext.getText() + "\n" + _etheadertext3.getText() + "\n" + _etheadertext4.getText() + "\n" + _etheadertext5.getText();

Solution

  • You can use text Spans to apply formatting to parts of a string.

    SpannableString spannablecontent=new SpannableString(content.toString());
    //set a Style Span to apply Typeface style    
    spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                                 0,spannablecontent.length(), 0);
    

    You can set RelativeSizeSpan to change the text sizes if required.

    And then finally, set the spanned string in a TextView.

    mTextView.setText(spannablecontent);