Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use html styles in strings with format arguments?

Tags:

java

android

In my app, I'd like to define a format string in strings.xml that looks like this (note the <b>...</b> tags):

<string name="location"><b>Location:</b> %1$s</string>

And then use getString(int, Object...) to substitute in a format argument:

String formattedString = getString(R.string.location, "Edmonton, AB");

This produces a value of "Location: Edmonton, AB". I'd like to get a value of "<b>Location:</b> Edmonton, AB".

Is there some way of doing this using string formats in strings.xml without splitting it up into two strings?

like image 852
Greg Avatar asked Nov 17 '11 16:11

Greg


2 Answers

From the docs:

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:

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

Make sure to escape the text you are passing in String.format()

String escapedUsername = TextUtils.htmlEncode(username);
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);
like image 199
Paul Burke Avatar answered Oct 01 '22 15:10

Paul Burke


Use String.Format. e.g.

  <string name="location"><![CDATA[<b>Location:</b> %s]]></string>

String formattedString = String.Format(getString(R.string.location), "Edmonton, AB");
like image 42
Kuffs Avatar answered Oct 01 '22 15:10

Kuffs