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