page.title=String Resources parent.title=Resource Types parent.link=available-resources.html page.metaDescription=Explains how to use string resources in your UI. @jd:body
A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:
All strings are capable of applying some styling markup and formatting arguments. For information about styling and formatting strings, see the section about Formatting and Styling.
A single string that can be referenced from the application or from other resource files (such as an XML layout).
Note: A string is a simple resource that is referenced
using the value provided in the {@code 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 {@code
res/values/filename.xml
R.string.string_name
@string/string_name
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name" >text_string</string> </resources>
res/values/strings.xml
:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources>
This layout XML applies a string to a View:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
This application code retrieves a string:
String string = {@link android.content.Context#getString(int) getString}(R.string.hello);
You can use either {@link android.content.Context#getString(int)} or {@link android.content.Context#getText(int)} to retrieve a string. {@link android.content.Context#getText(int)} will retain any rich text styling applied to the string.
An array of strings that can be referenced from the application.
Note: A string array is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine string array resources with other simple resources in the one XML file,
under one {@code
res/values/filename.xml
R.array.string_array_name
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item >text_string</item> </string-array> </resources>
res/values/strings.xml
:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> </string-array> </resources>
This application code retrieves a string array:
Resources res = {@link android.content.Context#getResources()}; String[] planets = res.{@link android.content.res.Resources#getStringArray(int) getStringArray}(R.array.planets_array);
Different languages have different rules for grammatical agreement with quantity. In English,
for example, the quantity 1 is a special case. We write "1 book", but for any other quantity we'd
write "n books". This distinction between singular and plural is very common, but other
languages make finer distinctions. The full set supported by Android is zero
,
one
, two
, few
, many
, and other
.
The rules for deciding which case to use for a given language and quantity can be very complex, so Android provides you with methods such as {@link android.content.res.Resources#getQuantityString(int,int) getQuantityString()} to select the appropriate resource for you.
Although historically called "quantity strings" (and still called that in API), quantity
strings should only be used for plurals. It would be a mistake to use quantity strings to
implement something like Gmail's "Inbox" versus "Inbox (12)" when there are unread messages, for
example. It might seem convenient to use quantity strings instead of an {@code if} statement,
but it's important to note that some languages (such as Chinese) don't make these grammatical
distinctions at all, so you'll always get the other
string.
The selection of which string to use is made solely based on grammatical necessity.
In English, a string for zero
will be ignored even if the quantity is 0, because 0
isn't grammatically different from 2, or any other number except 1 ("zero books", "one book",
"two books", and so on). Conversely, in Korean only the other
string will
ever be used.
Don't be misled either by the fact that, say, two
sounds like it could only apply to
the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one
another but differently to other quantities. Rely on your translator to know what distinctions
their language actually insists upon.
It's often possible to avoid quantity strings by using quantity-neutral formulations such as "Books: 1". This will make your life and your translators' lives easier, if it's a style that's in keeping with your application.
Note: A plurals collection is a simple resource that is
referenced using the value provided in the {@code name} attribute (not the name of the XML
file). As such, you can combine plurals resources with other simple resources in the one
XML file, under one {@code
res/values/filename.xml
R.plurals.plural_name
<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="plural_name"> <item quantity=["zero" | "one" | "two" | "few" | "many" | "other"] >text_string</item> </plurals> </resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="numberOfSongsAvailable"> <!-- As a developer, you should always supply "one" and "other" strings. Your translators will know which strings are actually needed for their language. Always include %d in "one" because translators will need to use %d for languages where "one" doesn't mean 1 (as explained above). --> <item quantity="one">%d song found.</item> <item quantity="other">%d songs found.</item> </plurals> </resources>
XML file saved at {@code res/values-pl/strings.xml}:
<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="numberOfSongsAvailable"> <item quantity="one">Znaleziono %d piosenkę.</item> <item quantity="few">Znaleziono %d piosenki.</item> <item quantity="other">Znaleziono %d piosenek.</item> </plurals> </resources>
Java code:
int count = getNumberOfsongsAvailable(); Resources res = {@link android.content.Context#getResources()}; String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);
When using the {@code getQuantityString()} method, you need to pass the {@code count} twice if your string includes string formatting with a number. For example, for the string {@code %d songs found}, the first {@code count} parameter selects the appropriate plural string and the second {@code count} parameter is inserted into the {@code %d} placeholder. If your plural strings do not include string formatting, you don't need to pass the third parameter to {@link android.content.res.Resources#getQuantityString(int,int) getQuantityString}.
Here are a few important things you should know about how to properly format and style your string resources.
If you have an apostrophe ('
) in your string, you must either
escape it with a backslash (\'
) or enclose the string in
double-quotes (""
). For example, here are some strings that do
and don't work:
<string name="good_example">This\'ll work</string> <string name="good_example_2">"This'll also work"</string> <string name="bad_example">This doesn't work</string> <!-- Causes a compile error -->
If you have a double-quote in your string, you must escape it
(\"
). Surrounding the string with single-quotes does
not work.
<string name="good_example">This is a \"good string\".</string> <string name="bad_example">This is a "bad string".</string> <!-- Quotes are stripped; displays as: This is a bad string. --> <string name="bad_example_2">'This is another "bad string".'</string> <!-- Causes a compile error -->
If you need to format your strings using {@code 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: {@code %1$s} is a string and {@code %2$d} is a decimal number. You can format the string with arguments from your application like this:
Resources res = {@link android.content.Context#getResources()}; String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
You can add styling to your strings with HTML markup. For example:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="welcome">Welcome to <b>Android</b>!</string> </resources>
Supported HTML elements include:
Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the {@code String.format(String, Object...)} method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with {@link android.text.Html#fromHtml(String)}, after the formatting takes place. For example:
<resources> <string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string> </resources>
In this formatted string, a {@code } element is added. Notice that the opening bracket is HTML-escaped, using the {@code <} notation.
Resources res = {@link android.content.Context#getResources()}; String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); CharSequence styledText = Html.fromHtml(text);
Because the {@link android.text.Html#fromHtml} method will format all HTML entities, be sure to escape any possible HTML characters in the strings you use with the formatted text, using {@link android.text.TextUtils#htmlEncode}. For instance, if you'll be passing a string argument to {@code String.format()} that may contain characters such as "<" or "&", then they must be escaped before formatting, so that when the formatted string is passed through {@link android.text.Html#fromHtml}, the characters come out the way they were originally written. For example:
String escapedUsername = TextUtil.{@link android.text.TextUtils#htmlEncode htmlEncode}(username); Resources res = {@link android.content.Context#getResources()}; String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount); CharSequence styledText = Html.fromHtml(text);
A {@link android.text.Spannable} is a text object that you can style with typeface properties such as color and font weight. You use {@link android.text.SpannableStringBuilder} to build your text and then apply styles defined in the {@link android.text.style} package to the text.
You can use the following helper methods to set up much of the work of creating spannable text:
/** * Returns a CharSequence that concatenates the specified array of CharSequence * objects and then applies a list of zero or more tags to the entire range. * * @param content an array of character sequences to apply a style to * @param tags the styled span objects to apply to the content * such as android.text.style.StyleSpan * */ private static CharSequence apply(CharSequence[] content, Object... tags) { SpannableStringBuilder text = new SpannableStringBuilder(); openTags(text, tags); for (CharSequence item : content) { text.append(item); } closeTags(text, tags); return text; } /** * Iterates over an array of tags and applies them to the beginning of the specified * Spannable object so that future text appended to the text will have the styling * applied to it. Do not call this method directly. */ private static void openTags(Spannable text, Object[] tags) { for (Object tag : tags) { text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK); } } /** * "Closes" the specified tags on a Spannable by updating the spans to be * endpoint-exclusive so that future text appended to the end will not take * on the same styling. Do not call this method directly. */ private static void closeTags(Spannable text, Object[] tags) { int len = text.length(); for (Object tag : tags) { if (len > 0) { text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { text.removeSpan(tag); } } }
The following bold
, italic
, and color
methods show you how to call the helper methods to apply
styles defined in the {@link android.text.style} package. You
can create similar methods to do other types of text styling.
/** * Returns a CharSequence that applies boldface to the concatenation * of the specified CharSequence objects. */ public static CharSequence bold(CharSequence... content) { return apply(content, new StyleSpan(Typeface.BOLD)); } /** * Returns a CharSequence that applies italics to the concatenation * of the specified CharSequence objects. */ public static CharSequence italic(CharSequence... content) { return apply(content, new StyleSpan(Typeface.ITALIC)); } /** * Returns a CharSequence that applies a foreground color to the * concatenation of the specified CharSequence objects. */ public static CharSequence color(int color, CharSequence... content) { return apply(content, new ForegroundColorSpan(color)); }
Here's an example of how to chain these methods to create a character sequence with different types of styling applied to individual words:
// Create an italic "hello, " a red "world", // and bold the entire sequence. CharSequence text = bold(italic(res.getString(R.string.hello)), color(Color.RED, res.getString(R.string.world)));