In Android it is possible to use placeholders in strings, such as:
<string name="number">My number is %1$d</string>
and then in Java code (inside a subclass of Activity
):
String res = getString(R.string.number); String formatted = String.format(res, 5);
or even simpler:
String formatted = getString(R.string.number, 5);
It is also possible to use some HTML tags in Android string resources:
<string name="underline"><u>Underline</u> example</string>
Since the String
itself cannot hold any information about formatting, one should use getText(int)
instead of getString(int)
method:
CharSequence formatted = getText(R.string.underline);
The returned CharSequence
can be then passed to Android widgets, such as TextView
, and the marked phrase will be underlined.
However, I could not find how to combine these two methodes, using formatted string together with placeholders:
<string name="underlined_number">My number is <u>%1$d</u></string>
How to process above resource in the Java code to display it in a TextView
, substituting %1$d
with an integer?
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
You should add them to a string resource file and then reference them from your layout. This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings. xml file. It is also extremely useful for supporting multiple languages as a separate strings.
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this: Resources res = getResources(); String text = res.getString(R. string.welcome_messages, username, mailCount);
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
Finally I managed to find a working solution and wrote my own method for replacing placeholders, preserving formatting:
public static CharSequence getText(Context context, int id, Object... args) { for(int i = 0; i < args.length; ++i) args[i] = args[i] instanceof String? TextUtils.htmlEncode((String)args[i]) : args[i]; return Html.fromHtml(String.format(Html.toHtml(new SpannedString(context.getText(id))), args)); }
This approach does not require to escape HTML tags manually neither in a string being formatted nor in strings that replace placeholders.
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