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). 241 242<p>Don't be misled either by the fact that, say, <code>two</code> sounds like it could only apply to 243the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one 244another but differently to other quantities. Rely on your translator to know what distinctions 245their language actually insists upon. 246 247<p>It's often possible to avoid quantity strings by using quantity-neutral formulations such as 248"Books: 1". This will make your life and your translators' lives easier, if it's a style that's 249in keeping with your application. 250 251<p class="note"><strong>Note:</strong> A plurals collection is a simple resource that is 252referenced using the value provided in the {@code name} attribute (not the name of the XML 253file). As such, you can combine plurals resources with other simple resources in the one 254XML file, under one {@code <resources>} element.</p> 255 256<dl class="xml"> 257 258<dt>file location:</dt> 259<dd><code>res/values/<em>filename</em>.xml</code><br/> 260The filename is arbitrary. The {@code <plurals>} element's {@code name} will be used as the 261resource ID.</dd> 262 263<dt>resource reference:</dt> 264<dd> 265In Java: <code>R.plurals.<em>plural_name</em></code> 266</dd> 267 268<dt>syntax:</dt> 269<dd> 270<pre class="stx"> 271<?xml version="1.0" encoding="utf-8"?> 272<<a href="#plurals-resources-element">resources</a>> 273 <<a href="#plurals-element">plurals</a> 274 name="<em>plural_name</em>"> 275 <<a href="#plurals-item-element">item</a> 276 quantity=["zero" | "one" | "two" | "few" | "many" | "other"] 277 ><em>text_string</em></item> 278 </plurals> 279</resources> 280</pre> 281</dd> 282 283<dt>elements:</dt> 284<dd> 285<dl class="tag-list"> 286 287 <dt id="plurals-resources-element"><code><resources></code></dt> 288 <dd><strong>Required.</strong> This must be the root node. 289 <p>No attributes.</p> 290 </dd> 291 <dt id="plurals-element"><code><plurals></code></dt> 292 <dd>A collection of strings, of which, one string is provided depending on the amount of 293something. Contains one or more {@code <item>} elements. 294 <p class="caps">attributes:</p> 295 <dl class="atn-list"> 296 <dt><code>name</code></dt> 297 <dd><em>String</em>. A name for the pair of strings. This name will be used as the 298resource ID.</dd> 299 </dl> 300 301 </dd> 302 <dt id="plurals-item-element"><code><item></code></dt> 303 <dd>A plural or singular string. The value can be a reference to another 304string resource. Must be a child of a {@code <plurals>} element. Beware that you must 305escape apostrophes and quotation marks. See <a href="#FormattingAndStyling">Formatting and 306Styling</a>, below, for information about to properly style and format your strings. 307 <p class="caps">attributes:</p> 308 <dl class="atn-list"> 309 <dt><code>quantity</code></dt> 310 <dd><em>Keyword</em>. A value indicating when this string should be used. Valid 311values, with non-exhaustive examples in parentheses: 312 <table> 313 <tr><th>Value</th><th>Description</th></tr> 314 <tr> 315 <td>{@code zero}</td><td>When the language requires special treatment of the number 0 (as in Arabic).</td> 316 </tr> 317 <tr> 318 <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> 319 </tr> 320 <tr> 321 <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> 322 </tr> 323 <tr> 324 <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> 325 </tr> 326 <tr> 327 <td>{@code many}</td><td>When the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese).</td> 328 </tr> 329 <tr> 330 <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> 331 </tr> 332 </table> 333 </dd> 334 </dl> 335 </dd> 336 337</dl> 338</dd> <!-- end elements --> 339 340<dt>example:</dt> 341<dd>XML file saved at {@code res/values/strings.xml}:</p> 342<pre> 343<?xml version="1.0" encoding="utf-8"?> 344<resources> 345 <plurals name="numberOfSongsAvailable"> 346 <item quantity="one">One song found.</item> 347 <item quantity="other">%d songs found.</item> 348 </plurals> 349</resources> 350</pre> 351 <p>XML file saved at {@code res/values-pl/strings.xml}:</p> 352<pre> 353<?xml version="1.0" encoding="utf-8"?> 354<resources> 355 <plurals name="numberOfSongsAvailable"> 356 <item quantity="one">Znaleziono jedną piosenkę.</item> 357 <item quantity="few">Znaleziono %d piosenki.</item> 358 <item quantity="other">Znaleziono %d piosenek.</item> 359 </plurals> 360</resources> 361</pre> 362 <p>Java code:</p> 363<pre> 364int count = getNumberOfsongsAvailable(); 365Resources res = {@link android.content.Context#getResources()}; 366String songsFound = res.<a 367href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)" 368>getQuantityString</a>(R.plurals.numberOfSongsAvailable, count, count); 369</pre> 370 371<p>When using the <a 372href="{@docRoot}reference/android/content/res/Resources.html#getQuantityString(int, int, java.lang.Object...)">{@code 373getQuantityString()}</a> method, you need to pass the {@code count} twice if your string includes 374<a href="#FormattingAndStyling">string formatting</a> with a number. For example, for the string 375{@code %d songs found}, the first {@code count} parameter selects the appropriate plural string and 376the second {@code count} parameter is inserted into the {@code %d} placeholder. If your plural 377strings do not include string formatting, you don't need to pass the third parameter to {@link 378android.content.res.Resources#getQuantityString(int,int) getQuantityString}.</p> 379</dd> <!-- end example --> 380 381</dl> 382 383 384 385 386 387 388 389 390<h2 id="FormattingAndStyling">Formatting and Styling</h2> 391 392<p>Here are a few important things you should know about how to properly 393format and style your string resources.</p> 394 395 396<h3>Escaping apostrophes and quotes</h3> 397 398<p>If you have an apostrophe or a quote in your string, you must either escape it or enclose the 399whole string in the other type of enclosing quotes. For example, here are some stings that 400do and don't work:</p> 401 402<pre> 403<string name="good_example">"This'll work"</string> 404<string name="good_example_2">This\'ll also work</string> 405<string name="bad_example">This doesn't work</string> 406<string name="bad_example_2">XML encodings don&apos;t work</string> 407</pre> 408 409 410<h3>Formatting strings</h3> 411 412<p>If you need to format your strings using <a 413href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 414java.lang.Object...)">{@code String.format(String, Object...)}</a>, 415then you can do so by putting 416your format arguments in the string resource. For example, with the following resource:</p> 417 418<pre> 419<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string> 420</pre> 421 422<p>In this example, the format string has two arguments: {@code %1$s} is a string and {@code %2$d} 423is a decimal number. You can format the string with arguments from your application like this:</p> 424 425<pre> 426Resources res = {@link android.content.Context#getResources()}; 427String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 428java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount); 429</pre> 430 431 432 433<h3 id="StylingWithHTML">Styling with HTML markup</h3> 434 435<p>You can add styling to your strings with HTML markup. For example:</p> 436<pre> 437<?xml version="1.0" encoding="utf-8"?> 438<resources> 439 <string name="welcome">Welcome to <b>Android</b>!</string> 440</resources> 441</pre> 442<p>Supported HTML elements include:</p> 443<ul> 444 <li>{@code <b>} for <b>bold</b> text.</li> 445 <li>{@code <i>} for <i>italic</i> text.</li> 446 <li>{@code <u>} for <u>underline</u> text.</li> 447</ul> 448 449<p>Sometimes you may want to create a styled text resource that is also used as a format 450string. Normally, this won't work because the <a 451href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 452java.lang.Object...)">{@code String.format(String, Object...)}</a> 453method will strip all the style 454information from the string. The work-around to this is to write the HTML tags with escaped 455entities, which are then recovered with {@link android.text.Html#fromHtml(String)}, 456after the formatting takes place. For example:</p> 457 458<ol> 459 <li>Store your styled text resource as an HTML-escaped string: 460<pre> 461<resources> 462 <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string> 463</resources> 464</pre> 465<p>In this formatted string, a {@code <b>} element is added. Notice that the opening bracket is 466HTML-escaped, using the {@code &lt;} notation.</p> 467 </li> 468 <li>Then format the string as usual, but also call {@link android.text.Html#fromHtml} to 469convert the HTML text into styled text: 470<pre> 471Resources res = {@link android.content.Context#getResources()}; 472String text = String.<a 473href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 474java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount); 475CharSequence styledText = Html.fromHtml(text); 476</pre> 477 </li> 478</ol> 479 480<p>Because the {@link android.text.Html#fromHtml} method will format all HTML entities, be sure to 481escape any possible HTML characters in the strings you use with the formatted text, using 482{@link android.text.TextUtils#htmlEncode}. For instance, if you'll be passing a string argument to 483<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 484java.lang.Object...)">{@code String.format()}</a> that may contain characters such as 485"<" or "&", then they must be escaped before formatting, so that when the formatted string 486is passed through {@link android.text.Html#fromHtml}, the characters come out the way they were 487originally written. For example:</p> 488<pre> 489String escapedUsername = TextUtil.{@link android.text.TextUtils#htmlEncode htmlEncode}(username); 490 491Resources res = {@link android.content.Context#getResources()}; 492String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String, 493java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), escapedUsername, mailCount); 494CharSequence styledText = Html.fromHtml(text); 495</pre> 496 497<h2 id="StylingWithSpannables">Styling with Spannables</h2> 498<p> 499A {@link android.text.Spannable} is a text object that you can style with 500typeface properties such as color and font weight. You use 501{@link android.text.SpannableStringBuilder} to build 502your text and then apply styles defined in the {@link android.text.style} 503package to the text. 504</p> 505 506<p>You can use the following helper methods to set up much of the work 507of creating spannable text:</p> 508 509<pre style="pretty-print"> 510/** 511 * Returns a CharSequence that concatenates the specified array of CharSequence 512 * objects and then applies a list of zero or more tags to the entire range. 513 * 514 * @param content an array of character sequences to apply a style to 515 * @param tags the styled span objects to apply to the content 516 * such as android.text.style.StyleSpan 517 * 518 */ 519private static CharSequence apply(CharSequence[] content, Object... tags) { 520 SpannableStringBuilder text = new SpannableStringBuilder(); 521 openTags(text, tags); 522 for (CharSequence item : content) { 523 text.append(item); 524 } 525 closeTags(text, tags); 526 return text; 527} 528 529/** 530 * Iterates over an array of tags and applies them to the beginning of the specified 531 * Spannable object so that future text appended to the text will have the styling 532 * applied to it. Do not call this method directly. 533 */ 534private static void openTags(Spannable text, Object[] tags) { 535 for (Object tag : tags) { 536 text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK); 537 } 538} 539 540/** 541 * "Closes" the specified tags on a Spannable by updating the spans to be 542 * endpoint-exclusive so that future text appended to the end will not take 543 * on the same styling. Do not call this method directly. 544 */ 545private static void closeTags(Spannable text, Object[] tags) { 546 int len = text.length(); 547 for (Object tag : tags) { 548 if (len > 0) { 549 text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 550 } else { 551 text.removeSpan(tag); 552 } 553 } 554} 555</pre> 556 557<p> 558The following <code>bold</code>, <code>italic</code>, and <code>color</code> 559methods show you how to call the helper methods to apply 560styles defined in the {@link android.text.style} package. You 561can create similar methods to do other types of text styling. 562</p> 563 564<pre style="pretty-print"> 565/** 566 * Returns a CharSequence that applies boldface to the concatenation 567 * of the specified CharSequence objects. 568 */ 569public static CharSequence bold(CharSequence... content) { 570 return apply(content, new StyleSpan(Typeface.BOLD)); 571} 572 573/** 574 * Returns a CharSequence that applies italics to the concatenation 575 * of the specified CharSequence objects. 576 */ 577public static CharSequence italic(CharSequence... content) { 578 return apply(content, new StyleSpan(Typeface.ITALIC)); 579} 580 581/** 582 * Returns a CharSequence that applies a foreground color to the 583 * concatenation of the specified CharSequence objects. 584 */ 585public static CharSequence color(int color, CharSequence... content) { 586 return apply(content, new ForegroundColorSpan(color)); 587} 588</pre> 589 590<p> 591Here's an example of how to chain these methods to create a character sequence 592with different types of styling applied to individual words: 593</p> 594 595<pre style="pretty-print"> 596// Create an italic "hello, " a red "world", 597// and bold the entire sequence. 598CharSequence text = bold(italic(res.getString(R.string.hello)), 599 color(Color.RED, res.getString(R.string.world))); 600</pre>