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?
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 <b>%2$d new messages</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);
Use String.Format. e.g.
<string name="location"><![CDATA[<b>Location:</b> %s]]></string>
String formattedString = String.Format(getString(R.string.location), "Edmonton, AB");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With