Updated 22 December 2016
In this blog,
we will get interact with the string placeholder. And see, is it possible to Concatenate multiple strings in XML?
OR
How to reference one string from another string in strings.xml?
If we want to Concatenate multiple strings in XML? or reference one string from another string in strings.xml? so what we can’t do with the strings,
1 2 3 4 |
<string name="music">Music</string> <string name="music_taste">@string/music</string> // gives "Music" <string name="music_taste">Rock @string/music</string> // always gives "Rock @string/music" <string name="music_taste">@string/music Pop </string> // gives compilation error |
Because here it will search for a String with reference @string/music Pop which does not exist.
So what we can do to want string placeholders which can be change dynamically.
“Formatting strings”, If you need to format your strings using String.format(String, Object…), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
1 |
<string name="my_welcome_messages">Welcome, %1$s! You have %2$d new notifications.</string> |
In this example, the format string has two arguments: %1$s
is a string and %2$d
is a decimal number. You can format the string with arguments from your application like this:
1 2 |
Resources res = getResources(); String text = String.format(res.getString(R.string.my_welcome_messages), name, notificationCount); |
So what can we do with music string,
1 2 |
<string name="music">Music</string> <string name="music_taste">%1$s @string/music</string> |
in java file,
1 2 |
Resources res = getResources(); String text = String.format(res.getString(R.string.music_taste), musicType); |
Example:
1 2 |
musicType = "Rock"; String text = String.format(res.getString(R.string.music_taste), musicType); |
output: Rock Music
1 2 |
musicType = "Pop"; String text = String.format(res.getString(R.string.music_taste), musicType); |
output: Pop Music
Refrence:
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.