Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have placeholders in strings.xml for runtime values?

Is it possible to have placeholders in string values in string.xml that can be assigned values at run time?

Example:

some string PLACEHOLDER1 some more string

like image 573
SoftReference Avatar asked Sep 07 '10 06:09

SoftReference


People also ask

Why are strings stored in xml?

Another reason for storing strings in xml is for localization. You can store different files for each different Locale or language, and Android will grab the correct file for the phone's selected Locale or language.

What is a string in xml?

Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one <resources> element. file location: res/values/filename.xml.


1 Answers

Formatting and Styling

Yes, see the following from String Resources: Formatting and Styling

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:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</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:

Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); 

Basic Usage

Note that getString has an overload that uses the string as a format string:

String text = res.getString(R.string.welcome_messages, username, mailCount); 

Plurals

If you need to handle plurals, use this:

<plurals name="welcome_messages">     <item quantity="one">Hello, %1$s! You have a new message.</item>     <item quantity="other">Hello, %1$s! You have %2$d new messages.</item> </plurals> 

The first mailCount param is used to decide which format to use (single or plural), the other params are your substitutions:

Resources res = getResources(); String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount); 

See String Resources: Plurals for more details.

like image 141
Megha Joshi - GoogleTV DevRel Avatar answered Oct 03 '22 09:10

Megha Joshi - GoogleTV DevRel