Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: getString() from resources loses any tags in the string

for example:

I have a string in the resources:

<string name="smth"><small>hey girls</small></string>

When I use it in the xml resource files (for example in some text view),

android:text="@string/smth"

no problem whatsoever. It takes into account the "small" tag. It makes the string smaller. But when I want to use it like this:

String smth = getString(R.string.smth);

someTextView.setText(Html.fromHtml(smth));

the string doesn't have any tags!!!

Any help appreciated. Dan

like image 884
Danail Avatar asked Mar 27 '12 14:03

Danail


2 Answers

Use HTML tags with escaped entities.

Your question is answered directly in the official documentation!

Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the String.format(String, Object...) method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place. For example:

Store your styled text resource as an HTML-escaped string:

<resources>
  <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
</resources>

In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the &lt; notation. Then format the string as usual, but also call fromHtml(String) to convert the HTML text into styled text:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
like image 74
Dheeraj Vepakomma Avatar answered Oct 22 '22 05:10

Dheeraj Vepakomma


Why not try to replace '<', '>' and '\' by the corresponding unicode characters?

Regards.

like image 13
Manitoba Avatar answered Oct 22 '22 05:10

Manitoba