Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Android dynamic text string in res/values

Tags:

android

Let's say I have this string:

Your player has a good keeper skill and a decent people skill

Now the part not in bold of the string is always the same, what is known at runtime is the part in bold.

So how could I do something like:

Your player has a {var1} keeper skill and a {var2} people skill

and then fill those vars at runtime with right values?

I do not want to concatenate strings like:

"You player has a"  + var1  + "keeper skill and a"  + var2 + "people skill"
like image 396
dierre Avatar asked Oct 04 '11 10:10

dierre


2 Answers

You need to see Android string resource guide. There is a way to provide static string which can be later formatted with variables.

http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

You will define string like

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

And later in code you can replace

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
like image 58
Rahul Choudhary Avatar answered Oct 19 '22 10:10

Rahul Choudhary


in Strings.xml

You player has a %1$d  keeper skill and a %2$d people skill

in java

getString(R.string.article_stats, var1, var2);
like image 37
Blackbelt Avatar answered Oct 19 '22 09:10

Blackbelt