1page.title=String Resources 2parent.title=Resource Types 3parent.link=available-resources.html 4@jd:body 5 6<p>A string resource provides text strings for your application 7with optional text styling and formatting. There are three types of resources that can provide 8your application with strings:</p> 9 10<dl> 11 <dt><a href="#String">String</a></dt> 12 <dd>XML resource that provides a single string.</dd> 13 <dt><a href="#StringArray">String Array</a></dt> 14 <dd>XML resource that provides an array of strings.</dd> 15 <dt><a href="#Plurals">Quantity Strings (Plurals)</a></dt> 16 <dd>XML resource that carries different strings for pluralization.</dd> 17</dl> 18 19<p>All strings are capable of applying some styling markup and formatting arguments. For 20information about styling and formatting strings, see the section about <a 21href="#FormattingAndStyling">Formatting and Styling</a>.</p> 22 23<h2 id="String">String</h2> 24 25<p>A single string that can be referenced from the application or from other resource files (such 26as an XML layout).</p> 27 28<p class="note"><strong>Note:</strong> A string is a simple resource that is referenced 29using the value provided in the {@code name} attribute (not the name of the XML file). So, you can 30combine string resources with other simple resources in the one XML file, 31under one {@code <resources>} element.</p> 32 33<dl class="xml"> 34 35<dt>file location:</dt> 36<dd><code>res/values/<em>filename</em>.xml</code><br/> 37The filename is arbitrary. The {@code <string>} element's {@code name} will be used as the 38resource ID.</dd> 39 40<dt>compiled resource datatype:</dt> 41<dd>Resource pointer to a {@link java.lang.String}.</dd> 42 43<dt>resource reference:</dt> 44<dd> 45In Java: <code>R.string.<em>string_name</em></code><br/> 46In XML:<code>@string/<em>string_name</em></code> 47</dd> 48 49<dt>syntax:</dt> 50<dd> 51<pre class="stx"> 52<?xml version="1.0" encoding="utf-8"?> 53<<a href="#string-resources-element">resources</a>> 54 <<a href="#string-element">string</a> 55 name="<em>string_name</em>" 56 ><em>text_string</em></string> 57</resources> 58</pre> 59</dd> 60 61<dt>elements:</dt> 62<dd> 63<dl class="tag-list"> 64 65 <dt id="string-resources-element"><code><resources></code></dt> 66 <dd><strong>Required.</strong> This must be the root node. 67 <p>No attributes.</p> 68 </dd> 69 <dt id="string-element"><code><string></code></dt> 70 <dd>A string, which can include styling tags. Beware that you must escape apostrophes and 71quotation marks. For more information about how to properly style and format your strings see <a 72href="#FormattingAndStyling">Formatting and Styling</a>, below. 73 <p class="caps">attributes:</p> 74 <dl class="atn-list"> 75 <dt><code>name</code></dt> 76 <dd><em>String</em>. A name for the string. This name will be used as the resource 77ID.</dd> 78 </dl> 79 </dd> 80 81</dl> 82</dd> <!-- end elements and attributes --> 83 84<dt>example:</dt> 85<dd>XML file saved at <code>res/values/strings.xml</code>: 86<pre> 87<?xml version="1.0" encoding="utf-8"?> 88<resources> 89 <string name="hello">Hello!</string> 90</resources> 91</pre> 92 93 <p>This layout XML applies a string to a View:</p> 94<pre> 95<TextView 96 android:layout_width="fill_parent" 97 android:layout_height="wrap_content" 98 <strong>android:text="@string/hello"</strong> /> 99</pre> 100 101 <p>This application code retrieves a string:</p> 102<pre> 103String string = {@link android.content.Context#getString(int) getString}(R.string.hello); 104</pre> 105<p>You can use either {@link android.content.Context#getString(int)} or 106{@link android.content.Context#getText(int)} to retrieve a string. {@link 107android.content.Context#getText(int)} will retain any rich text styling applied to the string.</p> 108 109</dd> <!-- end example --> 110 111</dl> 112 113 114 115 116 117 118 119 120 121<h2 id="StringArray">String Array</h2> 122 123<p>An array of strings that can be referenced from the application.</p> 124 125<p class="note"><strong>Note:</strong> A string array is a simple resource that is referenced 126using the value provided in the {@code name} attribute (not the name of the XML file). As 127such, you can combine string array resources with other simple resources in the one XML file, 128under one {@code <resources>} element.</p> 129 130<dl class="xml"> 131 132<dt>file location:</dt> 133<dd><code>res/values/<em>filename</em>.xml</code><br/> 134The filename is arbitrary. The {@code <string-array>} element's {@code name} will be used as the 135resource ID.</dd> 136 137<dt>compiled resource datatype:</dt> 138<dd>Resource pointer to an array of {@link java.lang.String}s.</dd> 139 140<dt>resource reference:</dt> 141<dd> 142In Java: <code>R.array.<em>string_array_name</em></code> 143</dd> 144 145<dt>syntax:</dt> 146<dd> 147<pre class="stx"> 148<?xml version="1.0" encoding="utf-8"?> 149<<a href="#string-array-resources-element">resources</a>> 150 <<a href="#string-array-element">string-array</a> 151 name="<em>string_array_name</em>"> 152 <<a href="#string-array-item-element">item</a> 153 ><em>text_string</em></item> 154 </string-array> 155</resources> 156</pre> 157</dd> 158 159<dt>elements:</dt> 160<dd> 161<dl class="tag-list"> 162 <dt id="string-array-resources-element"><code><resources></code></dt> 163 <dd><strong>Required.</strong> This must be the root node. 164 <p>No attributes.</p> 165 </dd> 166 <dt id="string-array-element"><code><string-array></code></dt> 167 <dd>Defines an array of strings. Contains one or more {@code <item>} elements. 168 <p class="caps">attributes:</p> 169 <dl class="atn-list"> 170 <dt><code>name</code></dt> 171 <dd><em>String</em>. A name for the array. This name will be used as the resource 172ID to reference the array.</dd> 173 </dl> 174 175 </dd> 176 <dt id="string-array-item-element"><code><item></code></dt> 177 <dd>A string, which can include styling tags. The value can be a reference to another 178string resource. Must be a child of a {@code <string-array>} element. Beware that you 179must escape apostrophes and 180quotation marks. See <a href="#FormattingAndStyling">Formatting and Styling</a>, below, for 181information about to properly style and format your strings. 182 <p>No attributes.</p> 183 </dd> 184</dl> 185</dd> <!-- end elements --> 186 187<dt>example:</dt> 188<dd>XML file saved at <code>res/values/strings.xml</code>: 189<pre> 190<?xml version="1.0" encoding="utf-8"?> 191<resources> 192 <string-array name="planets_array"> 193 <item>Mercury</item> 194 <item>Venus</item> 195 <item>Earth</item> 196 <item>Mars</item> 197 </string-array> 198</resources> 199</pre> 200 201 <p>This application code retrieves a string array:</p> 202<pre> 203Resources res = {@link android.content.Context#getResources()}; 204String[] planets = res.{@link android.content.res.Resources#getStringArray(int) 205getStringArray}(R.array.planets_array); 206</pre> 207</dd> <!-- end example --> 208 209</dl> 210 211 212 213 214 215 216 217<h2 id="Plurals">Quantity Strings (Plurals)</h2> 218 219<p>Different languages have different rules for grammatical agreement with quantity. In English, 220for example, the quantity 1 is a special case. We write "1 book", but for any other quantity we'd 221write "<i>n</i> books". This distinction between singular and plural is very common, but other 222languages make finer distinctions. The full set supported by Android is <code>zero</code>, 223<code>one</code>, <code>two</code>, <code>few</code>, <code>many</code>, and <code>other</code>. 224 225<p>The rules for deciding which case to use for a given language and quantity can be very complex, 226so Android provides you with methods such as 227{@link android.content.res.Resources#getQuantityString(int,int) getQuantityString()} to select 228the appropriate resource for you. 229 230<p>Although historically called "quantity strings" (and still called that in API), quantity 231strings should <i>only</i> be used for plurals. It would be a mistake to use quantity strings to 232implement something like Gmail's "Inbox" versus "Inbox (12)" when there are unread messages, for 233example. It might seem convenient to use quantity strings instead of an {@code if} statement, 234but it's important to note that some languages (such as Chinese) don't make these grammatical 235distinctions at all, so you'll always get the <code>other</code> string. 236 237<p>The selection of which string to use is made solely based on grammatical <i>necessity</i>. 238In English, a string for <code>zero</code> will be ignored even if the quantity is 0, because 0 239isn't grammatically different from 2, or any other number except 1 ("zero books", "one book", 240"two books", and so on). Conversely, in Korean <i>only</i> the <code>other</code> string will 241ever be used. 242 243<p>Don't be misled either by the fact that, say, <code>two</code> sounds like it could only apply to 244the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one 245another but differently to other quantities. Rely on your translator to know what distinctions 246their language actually insists upon. 247 248<p>It's often possible to avoid quantity strings by using quantity-neutral formulations such as 249"Books: 1". This will make your life and your translators' lives easier, if it's a style that's 250in keeping with your application. 251 252<p class="note"><strong>Note:</strong> A plurals collection is a simple resource that is 253referenced using the value provided in the {@code name} attribute (not the name of the XML 254file). As such, you can combine plurals resources with other simple resources in the one 255XML file, under one {@code <resources>} element.</p> 256 257<dl class="xml"> 258 259<dt>file location:</dt> 260<dd><code>res/values/<em>filename</em>.xml</code><br/> 261The filename is arbitrary. The {@code <plurals>} element's {@code name} will be used as the 262resource ID.</dd> 263 264<dt>resource reference:</dt> 265<dd> 266In Java: <code>R.plurals.<em>plural_name</em></code> 267</dd> 268 269<dt>syntax:</dt> 270<dd> 271<pre class="stx"> 272<?xml version="1.0" encoding="utf-8"?> 273<<a href="#plurals-resources-element">resources</a>> 274 <<a href="#plurals-element">plurals</a> 275 name="<em>plural_name</em>"> 276 <<a href="#plurals-item-element">item</a> 277 quantity=["zero" | "one" | "two" | "few" | "many" | "other"] 278 ><em>text_string</em></item> 279 </plurals> 280</resources> 281</pre> 282</dd> 283 284<dt>elements:</dt> 285<dd> 286<dl class="tag-list"> 287 288 <dt id="plurals-resources-element"><code><resources></code></dt> 289 <dd><strong>Required.</strong> This must be the root node. 290 <p>No attributes.</p> 291 </dd> 292 <dt id="plurals-element"><code><plurals></code></dt> 293 <dd>A collection of strings, of which, one string is provided depending on the amount of 294something. Contains one or more {@code <item>} elements. 295 <p class="caps">attributes:</p> 296 <dl class="atn-list"> 297 <dt><code>name</code></dt> 298 <dd><em>String</em>. A name for the pair of strings. This name will be used as the 299resource ID.</dd> 300 </dl> 301 302 </dd> 303 <dt id="plurals-item-element"><code><item></code></dt> 304 <dd>A plural or singular string. The value can be a reference to another 305string resource. Must be a child of a {@code <plurals>} element. Beware that you must 306escape apostrophes and quotation marks. See <a href="#FormattingAndStyling">Formatting and 307Styling</a>, below, for information about to properly style and format your strings. 308 <p class="caps">attributes:</p> 309 <dl class="atn-list"> 310 <dt><code>quantity</code></dt> 311 <dd><em>Keyword</em>. A value indicating when this string should be used. Valid 312values, with non-exhaustive examples in parentheses: 313 <table> 314 <tr><th>Value</th><th>Description</th></tr> 315 <tr> 316 <td>{@code zero}</td><td>When the language requires special treatment of the number 0 (as in Arabic).</td> 317 </tr> 318 <tr> 319 <td>{@code one}</td><td>When the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number ending in 1 but not ending in 11 is in this class).</td> 320 </tr> 321 <tr> 322 <td>{@code two}</td><td>When the language requires special treatment of numbers like two (as with 2 in Welsh, or 102 in Slovenian).</td> 323 </tr> 324 <tr> 325 <td>{@code few}</td><td>When the language requires special treatment of "small" numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in Polish).</td> 326 </tr> 327 <tr> 328 <td>{@code many}</td><td>When the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese).</td> 329 </tr> 330 <tr> 331 <td>{@code other}</td><td>When the language does not require special treatment of the given quantity (as with all numbers in Chinese, or 42 in English).</td> 332 </tr> 333 </table> 334 </dd> 335 </dl> 336 </dd> 337 338</dl> 339</dd> <!-- end elements --> 340 341<dt>example:</dt> 342<dd>XML file saved at {@code res/values/strings.xml}:</p> 343<pre> 344<?xml version="1.0" encoding="utf-8"?> 345<resources> 346 <plurals name="numberOfSongsAvailable"> 347 <!-- 348 As a developer, you should always supply "one" and "other" 349 strings. Your translators will know which strings are actually 350 needed for their language. Always include %d in "one" because 351 translators will need to use %d for languages where "one" 352 doesn't mean 1 (as explained above). 353 --> 354 <item quantity="one">%d song found.</item> 355 <item quantity="other">%d songs found.</item> 356 </plurals> 357</resources> 358</pre> 359 <p>XML file saved at {@code res/values-pl/strings.xml}:</p> 360<pre> 361<?xml version="1.0" encoding="utf-8"?> 362<resources> 363 <plurals name="numberOfSongsAvailable"> 364 <item quantity="one">Znaleziono %d piosenkę.</item> 365 <item quantity="few">Znaleziono %d piosenki.</item> 366 <item quantity="other">Znaleziono %d piosenek.</item> 367 </plurals> 368</resources> 369</pre> 370 <p>Java code:</p> 371<pre> 372int count = getNumberOfsongsAvailable(); 373Resources res = {@link android.content.Context#getResources()}; 374String songsFound = res.<a 375href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)" 376>getQuantityString</a>(R.plurals.numberOfSongsAvailable, count, count); 377</pre> 378 379<p>When using the <a 380href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)">{@code 381getQuantityString()}</a> method, you need to pass the {@code count} twice if your string includes 382<a href="#FormattingAndStyling">string formatting</a> with a number. For example, for the string 383{@code %d songs found}, the first {@code count} parameter selects the appropriate plural string and 384the second {@code count} parameter is inserted into the {@code %d} placeholder. If your plural 385strings do not include string formatting, you don't need to pass the third parameter to {@link 386android.content.res.Resources#getQuantityString(int,int) getQuantityString}.</p> 387</dd> <!-- end example --> 388 389</dl> 390 391 392 393 394 395 396 397 398<h2 id="FormattingAndStyling">Formatting and Styling</h2> 399 400<p>Here are a few important things you should know about how to properly 401format and style your string resources.</p> 402 403 404<h3>Escaping apostrophes and quotes</h3> 405 406<p>If you have an apostrophe or a quote in your string, you must either escape it or enclose the 407whole string in the other type of enclosing quotes. For example, here are some stings that 408do and don't work:</p> 409 410<pre> 411<string name="good_example">"This'll work"</string> 412<string name="good_example_2">This\'ll also work</string> 413<string name="bad_example">This doesn't work</string> 414<string name="bad_example_2">XML encodings don&apos;t work</string> 415</pre> 416 417 418<h3>Formatting strings</h3> 419 420<p>If you need to format your strings using <a 421href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 422java.lang.Object...)">{@code String.format(String, Object...)}</a>, 423then you can do so by putting 424your format arguments in the string resource. For example, with the following resource:</p> 425 426<pre> 427<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string> 428</pre> 429 430<p>In this example, the format string has two arguments: {@code %1$s} is a string and {@code %2$d} 431is a decimal number. You can format the string with arguments from your application like this:</p> 432 433<pre> 434Resources res = {@link android.content.Context#getResources()}; 435String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 436java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount); 437</pre> 438 439 440 441<h3 id="StylingWithHTML">Styling with HTML markup</h3> 442 443<p>You can add styling to your strings with HTML markup. For example:</p> 444<pre> 445<?xml version="1.0" encoding="utf-8"?> 446<resources> 447 <string name="welcome">Welcome to <b>Android</b>!</string> 448</resources> 449</pre> 450<p>Supported HTML elements include:</p> 451<ul> 452 <li>{@code <b>} for <b>bold</b> text.</li> 453 <li>{@code <i>} for <i>italic</i> text.</li> 454 <li>{@code <u>} for <u>underline</u> text.</li> 455</ul> 456 457<p>Sometimes you may want to create a styled text resource that is also used as a format 458string. Normally, this won't work because the <a 459href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 460java.lang.Object...)">{@code String.format(String, Object...)}</a> 461method will strip all the style 462information from the string. The work-around to this is to write the HTML tags with escaped 463entities, which are then recovered with {@link android.text.Html#fromHtml(String)}, 464after the formatting takes place. For example:</p> 465 466<ol> 467 <li>Store your styled text resource as an HTML-escaped string: 468<pre> 469<resources> 470 <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string> 471</resources> 472</pre> 473<p>In this formatted string, a {@code <b>} element is added. Notice that the opening bracket is 474HTML-escaped, using the {@code &lt;} notation.</p> 475 </li> 476 <li>Then format the string as usual, but also call {@link android.text.Html#fromHtml} to 477convert the HTML text into styled text: 478<pre> 479Resources res = {@link android.content.Context#getResources()}; 480String text = String.<a 481href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 482java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount); 483CharSequence styledText = Html.fromHtml(text); 484</pre> 485 </li> 486</ol> 487 488<p>Because the {@link android.text.Html#fromHtml} method will format all HTML entities, be sure to 489escape any possible HTML characters in the strings you use with the formatted text, using 490{@link android.text.TextUtils#htmlEncode}. For instance, if you'll be passing a string argument to 491<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 492java.lang.Object...)">{@code String.format()}</a> that may contain characters such as 493"<" or "&", then they must be escaped before formatting, so that when the formatted string 494is passed through {@link android.text.Html#fromHtml}, the characters come out the way they were 495originally written. For example:</p> 496<pre> 497String escapedUsername = TextUtil.{@link android.text.TextUtils#htmlEncode htmlEncode}(username); 498 499Resources res = {@link android.content.Context#getResources()}; 500String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 501java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), escapedUsername, mailCount); 502CharSequence styledText = Html.fromHtml(text); 503</pre> 504 505<h2 id="StylingWithSpannables">Styling with Spannables</h2> 506<p> 507A {@link android.text.Spannable} is a text object that you can style with 508typeface properties such as color and font weight. You use 509{@link android.text.SpannableStringBuilder} to build 510your text and then apply styles defined in the {@link android.text.style} 511package to the text. 512</p> 513 514<p>You can use the following helper methods to set up much of the work 515of creating spannable text:</p> 516 517<pre style="pretty-print"> 518/** 519 * Returns a CharSequence that concatenates the specified array of CharSequence 520 * objects and then applies a list of zero or more tags to the entire range. 521 * 522 * @param content an array of character sequences to apply a style to 523 * @param tags the styled span objects to apply to the content 524 * such as android.text.style.StyleSpan 525 * 526 */ 527private static CharSequence apply(CharSequence[] content, Object... tags) { 528 SpannableStringBuilder text = new SpannableStringBuilder(); 529 openTags(text, tags); 530 for (CharSequence item : content) { 531 text.append(item); 532 } 533 closeTags(text, tags); 534 return text; 535} 536 537/** 538 * Iterates over an array of tags and applies them to the beginning of the specified 539 * Spannable object so that future text appended to the text will have the styling 540 * applied to it. Do not call this method directly. 541 */ 542private static void openTags(Spannable text, Object[] tags) { 543 for (Object tag : tags) { 544 text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK); 545 } 546} 547 548/** 549 * "Closes" the specified tags on a Spannable by updating the spans to be 550 * endpoint-exclusive so that future text appended to the end will not take 551 * on the same styling. Do not call this method directly. 552 */ 553private static void closeTags(Spannable text, Object[] tags) { 554 int len = text.length(); 555 for (Object tag : tags) { 556 if (len > 0) { 557 text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 558 } else { 559 text.removeSpan(tag); 560 } 561 } 562} 563</pre> 564 565<p> 566The following <code>bold</code>, <code>italic</code>, and <code>color</code> 567methods show you how to call the helper methods to apply 568styles defined in the {@link android.text.style} package. You 569can create similar methods to do other types of text styling. 570</p> 571 572<pre style="pretty-print"> 573/** 574 * Returns a CharSequence that applies boldface to the concatenation 575 * of the specified CharSequence objects. 576 */ 577public static CharSequence bold(CharSequence... content) { 578 return apply(content, new StyleSpan(Typeface.BOLD)); 579} 580 581/** 582 * Returns a CharSequence that applies italics to the concatenation 583 * of the specified CharSequence objects. 584 */ 585public static CharSequence italic(CharSequence... content) { 586 return apply(content, new StyleSpan(Typeface.ITALIC)); 587} 588 589/** 590 * Returns a CharSequence that applies a foreground color to the 591 * concatenation of the specified CharSequence objects. 592 */ 593public static CharSequence color(int color, CharSequence... content) { 594 return apply(content, new ForegroundColorSpan(color)); 595} 596</pre> 597 598<p> 599Here's an example of how to chain these methods to create a character sequence 600with different types of styling applied to individual words: 601</p> 602 603<pre style="pretty-print"> 604// Create an italic "hello, " a red "world", 605// and bold the entire sequence. 606CharSequence text = bold(italic(res.getString(R.string.hello)), 607 color(Color.RED, res.getString(R.string.world))); 608</pre> 609