Wednesday, 8 June 2016

How to display html in TextView? spanned doesn't support inline css


Android TextView gives very limited text styles, just normal, middle and large size.

Spanned gives you the ability to show htmls onto a TextView.

String displayString = "<b> tips:</b>&nbsp;&nbsp;&nbsp;" + message + "<br/>";
Spanned displayHtml = Html.fromHtml(displayString);
textView.setText(displayHtml);


However, Spanned does not support css.

<h1 style="color:blue;">This is a Blue Heading</h1>

For above html,  Android TextView will only show the H1 in black.

Reason:
 Spanned does not support css

Solution:
 Spanned does not support css, so you should use HTML tag to replace CSS (not all css can be replaced by HTML tags):

<H1><font color="red">Tips:</font></H1>


Tips:  
1. If you want to put your html into res/values/string.xml, you should do: <![CDATA[ your html ]]>  e.g.    
  <string name="yourhtml">  
    <![CDATA[
    
    <H1><font color="red">Tips:</font></H1> love peter.

    ]]>
</string>
2. res/values/string.xml doesn't like  single quote, please use double quotes

Thanks

No comments:

Post a comment