Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments in string resource for a string with styling in android

I have a String in my strings.xml file such as

  <string name="my_text">Hello <b>$%1$s</b>, android is cool <b>bold me</b></string>

The only way to retrieve the text with styling for bolding is using resources.getText(R.string.my_text);

Although the issue is getText does not take additional parameters for the arguments I wish to provide such as the method getString that takes arguments such as resources.getString(R.string.my_text, "I WILL BE BOLDED")

If I use getString I lose the bold, if I use getText I cant pass arguments how do I obtain both?

like image 856
Jada Avatar asked Feb 03 '23 22:02

Jada


2 Answers

To expand upon Sagar's answer, set up the string resource using CDATA:

<string name="test"><![CDATA[When no one was looking, Lex Luthor took <b>%s</b> cakes. He took %d cakes. That\'s as many as %s %s. And that\'s terrible.]]></string>

Then, retrieve the string resource using getString() and use HtmlCompat to handle the formatting:

HtmlCompat.fromHtml(getString(R.string.test, "forty", 40, "four", "tens"), HtmlCompat.FROM_HTML_MODE_COMPACT)

NOTE: The author of the answer can neither confirm nor deny that some number of cakes were consumed in the creation of this answer. However, no actual supervillains were involved, as far as you are aware.

like image 79
CommonsWare Avatar answered Feb 06 '23 13:02

CommonsWare


strings.xml

<string name="my_text">Hello &lt;b>$%1$s &lt;/b>, android is cool &lt;b>bold me &lt;/b></string>

code

String.format(res.getString(R.my_text.welcome_messages), "I WILL BE BOLDED");

like image 25
Philipp Avatar answered Feb 06 '23 11:02

Philipp