Take the 2-minute tour ×

I have a string resource called "foo". It may be a simple string... or it may contain HTML. This may change over time: I should be able to box it up as at least a SpannableString immediately upon reading whether it's HTML or not (but how??)

I want to get that raw CharSequence and first be able to display it as-is (the exact characters, not Android's "interpretation" of it). Right now I can't do that... toString() decides to rip out the parts it doesn't think I want to see.

I'd then like to be able to create a SpannableString from this and other Strings or SpannableStrings via concatenation using some method (none of the normal ones work). I'd like to then use that SpannableString to display the HTML-formatted text in a TextView.

This shouldn't be difficult, but clearly I'm not doing it right (there's very little info out there about this that I've found so far). Surely there is a way to accurately interconvert between between Strings, SpannedStrings and even Spannablestrings, without losing the markups along the way?

Note that I've already played with the somewhat broken Linkify, but I want better control over the process (no dangling unformatted "/"s, proper hrefs, etc.) I can get this all to work IF I stay in HTML at all steps, though I can't concatenate anything.

Edit 1: I've learned I can use the following to always ensure I get my raw string (instead of whatever Android decides it thinks the CharSequence really is). Nice... now, how to coax this into a SpannableString?

<string name="foo"><![CDATA[
    <b>Some bold</b>

Edit 2: Not sure why this didn't work earlier, but... if foo1 and foo2 are strings marked up as above (as CDATA), then one can apparently do this:

String foo1 = (String)getResources().getText(R.string.foo1);
String foo2 = (String)getResources().getText(R.string.foo2);
SpannedString bar = new SpannedString(Html.fromHtml(foo1+foo2));

Curious: is there a more straightforward solution than this? Is this CDATA business actually necessary? It seems convoluted (but not as convoluted as never quite knowing what the resource type will be... String, Spannable, etc.)

share|improve this question
It looks like you answered your own question here. Your foo1, foo2 example above seems fine. If you don't have another concrete question you should answer your question so it is removed from the unanswered section. CDATA is necessary to embed HTML in XML because otherwise the html elements will be indistinguishable from the enclosing XML. –  Tom Dignan May 17 '12 at 1:09
add comment

1 Answer

up vote 1 down vote accepted

It appears there isn't a more straightforward way to accomplish this.

share|improve this answer
add comment

Your Answer


