Search code examples
androidtextviewandroid-textattributes

Android: formatting portion of text doesn't work


In my strings.xml file I have defined the following:

<string name="mystring"><b>Bold text</b>Non-bold text</string>

It should work, as it's specified here. But actually only bold text is displayed, and the other part of text is gone.


Solution

  • taken from this SO thread

    use this

    textView.setText(Html.fromHtml(someText));
    

    or from xml by this way

    You CAN include raw HTML in strings.xml, as long as you wrap it in

    <![CDATA[ ...raw html... ]]>
    

    Example:

    <string name="nice_html">
    <![CDATA[
    <p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
    <p>This is another paragraph of the same string.</p>
    ]]>
    </string>
    

    Then, in your code:

    TextView foo = (TextView)findViewById(R.id.foo);
    foo.setText(Html.fromHtml(getString(R.string.nice_html)));
    

    you can also backslash-escape apostrophes/single-quotes inside the CDATA block, so you can have things like <b>can\'t</b> instead of the infinitely-uglier <b>can&apos;t</b>