blob: 743e69233645b10b79d7e0159632efc6d5ff7c22 [file] [log] [blame]
Scott Main208b9c52010-02-09 18:48:27 -08001page.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>
Elliott Hughes1ad636c2010-07-01 16:51:48 -070015 <dt><a href="#Plurals">Quantity Strings (Plurals)</a></dt>
Elliott Hughes0cd01672012-09-25 16:15:35 -070016 <dd>XML resource that carries different strings for pluralization.</dd>
Scott Main208b9c52010-02-09 18:48:27 -080017</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
Scott Main208b9c52010-02-09 18:48:27 -080023<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 &lt;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 &lt;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&lt;?xml version="1.0" encoding="utf-8"?>
53&lt;<a href="#string-resources-element">resources</a>>
54 &lt;<a href="#string-element">string</a>
55 name="<em>string_name</em>"
56 &gt;<em>text_string</em>&lt;/string&gt;
57&lt;/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>&lt;resources&gt;</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>&lt;string&gt;</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&lt;?xml version="1.0" encoding="utf-8"?>
88&lt;resources>
89 &lt;string name="hello">Hello!&lt;/string>
90&lt;/resources>
91</pre>
92
93 <p>This layout XML applies a string to a View:</p>
94<pre>
95&lt;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
Scott Main71825f42011-07-14 10:24:18 -0700106{@link android.content.Context#getText(int)} to retrieve a string. {@link
Scott Main208b9c52010-02-09 18:48:27 -0800107android.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 &lt;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 &lt;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&lt;?xml version="1.0" encoding="utf-8"?>
149&lt;<a href="#string-array-resources-element">resources</a>>
150 &lt;<a href="#string-array-element">string-array</a>
151 name="<em>string_array_name</em>">
152 &lt;<a href="#string-array-item-element">item</a>
153 &gt;<em>text_string</em>&lt;/item&gt;
154 &lt;/string-array>
155&lt;/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>&lt;resources&gt;</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>&lt;string-array&gt;</code></dt>
167 <dd>Defines an array of strings. Contains one or more {@code &lt;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>&lt;item&gt;</code></dt>
Scott Kennedy7ed189e2013-01-11 22:31:43 -0800177 <dd>A string, which can include styling tags. The value can be a reference to another
Scott Main208b9c52010-02-09 18:48:27 -0800178string resource. Must be a child of a {@code &lt;string-array&gt;} 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&lt;?xml version="1.0" encoding="utf-8"?>
191&lt;resources>
192 &lt;string-array name="planets_array">
193 &lt;item>Mercury&lt;/item>
194 &lt;item>Venus&lt;/item>
195 &lt;item>Earth&lt;/item>
196 &lt;item>Mars&lt;/item>
197 &lt;/string-array>
198&lt;/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
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700217<h2 id="Plurals">Quantity Strings (Plurals)</h2>
Scott Main208b9c52010-02-09 18:48:27 -0800218
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700219<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
Elliott Hughes0cd01672012-09-25 16:15:35 -0700230<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",
Elliott Hughes1fe7d492014-05-23 13:28:33 -0700240"two books", and so on). Conversely, in Korean <i>only</i> the <code>other</code> string will
241ever be used.
Elliott Hughes0cd01672012-09-25 16:15:35 -0700242
243<p>Don't be misled either by the fact that, say, <code>two</code> sounds like it could only apply to
Scott Main71825f42011-07-14 10:24:18 -0700244the quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like one
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700245another 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.
Scott Main208b9c52010-02-09 18:48:27 -0800251
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 &lt;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 &lt;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&lt;?xml version="1.0" encoding="utf-8"?>
273&lt;<a href="#plurals-resources-element">resources</a>>
274 &lt;<a href="#plurals-element">plurals</a>
275 name="<em>plural_name</em>">
276 &lt;<a href="#plurals-item-element">item</a>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700277 quantity=["zero" | "one" | "two" | "few" | "many" | "other"]
Scott Main208b9c52010-02-09 18:48:27 -0800278 &gt;<em>text_string</em>&lt;/item>
279 &lt;/plurals>
280&lt;/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>&lt;resources&gt;</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>&lt;plurals&gt;</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 &lt;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>&lt;item&gt;</code></dt>
Scott Kennedyd7ec7422013-01-15 19:33:56 -0800304 <dd>A plural or singular string. The value can be a reference to another
Scott Main208b9c52010-02-09 18:48:27 -0800305string resource. Must be a child of a {@code &lt;plurals&gt;} 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>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700311 <dd><em>Keyword</em>. A value indicating when this string should be used. Valid
312values, with non-exhaustive examples in parentheses:
Scott Main208b9c52010-02-09 18:48:27 -0800313 <table>
314 <tr><th>Value</th><th>Description</th></tr>
315 <tr>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700316 <td>{@code zero}</td><td>When the language requires special treatment of the number 0 (as in Arabic).</td>
Scott Main208b9c52010-02-09 18:48:27 -0800317 </tr>
318 <tr>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700319 <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>
Elliott Hughes0cd01672012-09-25 16:15:35 -0700322 <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>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700323 </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>
Elliott Hughes0cd01672012-09-25 16:15:35 -0700331 <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>
Scott Main208b9c52010-02-09 18:48:27 -0800332 </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&lt;?xml version="1.0" encoding="utf-8"?>
345&lt;resources>
346 &lt;plurals name="numberOfSongsAvailable">
Elliott Hughes1fe7d492014-05-23 13:28:33 -0700347 &lt;!--
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 &lt;item quantity="one">%d song found.&lt;/item>
Scott Main208b9c52010-02-09 18:48:27 -0800355 &lt;item quantity="other">%d songs found.&lt;/item>
356 &lt;/plurals>
357&lt;/resources>
358</pre>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700359 <p>XML file saved at {@code res/values-pl/strings.xml}:</p>
360<pre>
361&lt;?xml version="1.0" encoding="utf-8"?>
362&lt;resources>
363 &lt;plurals name="numberOfSongsAvailable">
Elliott Hughes1fe7d492014-05-23 13:28:33 -0700364 &lt;item quantity="one">Znaleziono %d piosenk&#x0119;.&lt;/item>
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700365 &lt;item quantity="few">Znaleziono %d piosenki.&lt;/item>
366 &lt;item quantity="other">Znaleziono %d piosenek.&lt;/item>
367 &lt;/plurals>
368&lt;/resources>
369</pre>
Scott Main208b9c52010-02-09 18:48:27 -0800370 <p>Java code:</p>
371<pre>
372int count = getNumberOfsongsAvailable();
373Resources res = {@link android.content.Context#getResources()};
Scott Main8edad6f2012-03-09 10:55:50 -0800374String 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);
Scott Main208b9c52010-02-09 18:48:27 -0800377</pre>
Scott Main8edad6f2012-03-09 10:55:50 -0800378
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
Scott Main71825f42011-07-14 10:24:18 -0700382<a href="#FormattingAndStyling">string formatting</a> with a number. For example, for the string
Scott Mainff8ba652011-07-14 13:56:28 -0700383{@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>
Scott Main208b9c52010-02-09 18:48:27 -0800387</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
Andrew Solovaya967cad2015-04-02 15:10:51 -0700404<h3 id="escaping_quotes">Escaping apostrophes and quotes</h3>
Scott Main208b9c52010-02-09 18:48:27 -0800405
Andrew Solovaya967cad2015-04-02 15:10:51 -0700406<p>
407 If you have an apostrophe (<code>'</code>) in your string, you must either
408 escape it with a backslash (<code>\'</code>) or enclose the string in
409 double-quotes (<code>""</code>). For example, here are some strings that do
410 and don't work:
411</p>
Scott Main208b9c52010-02-09 18:48:27 -0800412
413<pre>
Andrew Solovaya967cad2015-04-02 15:10:51 -0700414&lt;string name="good_example">This\'ll work&lt;/string>
415&lt;string name="good_example_2">"This'll also work"&lt;/string>
Scott Main208b9c52010-02-09 18:48:27 -0800416&lt;string name="bad_example">This doesn't work&lt;/string>
Andrew Solovaya967cad2015-04-02 15:10:51 -0700417 &lt;!-- Causes a compile error -->
Scott Main208b9c52010-02-09 18:48:27 -0800418</pre>
419
Andrew Solovaya967cad2015-04-02 15:10:51 -0700420<p>
421 If you have a double-quote in your string, you must escape it
422 (<code>\"</code>). Surrounding the string with single-quotes does
423 <em>not</em> work.
424</p>
425
426<pre>
427&lt;string name="good_example">This is a \"good string\".&lt;/string>
428&lt;string name="bad_example">This is a "bad string".&lt;/string>
429 &lt;!-- Quotes are stripped; displays as: This is a bad string. -->
430&lt;string name="bad_example_2">'This is another "bad string".'&lt;/string>
431 &lt;!-- Causes a compile error -->
432</pre>
Scott Main208b9c52010-02-09 18:48:27 -0800433
434<h3>Formatting strings</h3>
435
436<p>If you need to format your strings using <a
437href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
438java.lang.Object...)">{@code String.format(String, Object...)}</a>,
439then you can do so by putting
440your format arguments in the string resource. For example, with the following resource:</p>
441
442<pre>
443&lt;string name="welcome_messages">Hello, %1$s! You have %2$d new messages.&lt;/string>
444</pre>
445
446<p>In this example, the format string has two arguments: {@code %1$s} is a string and {@code %2$d}
Scott Main71825f42011-07-14 10:24:18 -0700447is a decimal number. You can format the string with arguments from your application like this:</p>
Scott Main208b9c52010-02-09 18:48:27 -0800448
449<pre>
450Resources res = {@link android.content.Context#getResources()};
451String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
452java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount);
453</pre>
454
455
456
Robert Ly37cb8d72014-05-08 15:02:11 -0700457<h3 id="StylingWithHTML">Styling with HTML markup</h3>
Scott Main208b9c52010-02-09 18:48:27 -0800458
459<p>You can add styling to your strings with HTML markup. For example:</p>
460<pre>
461&lt;?xml version="1.0" encoding="utf-8"?>
462&lt;resources>
463 &lt;string name="welcome">Welcome to &lt;b>Android&lt;/b>!&lt;/string>
464&lt;/resources>
465</pre>
466<p>Supported HTML elements include:</p>
467<ul>
468 <li>{@code &lt;b>} for <b>bold</b> text.</li>
469 <li>{@code &lt;i>} for <i>italic</i> text.</li>
470 <li>{@code &lt;u>} for <u>underline</u> text.</li>
471</ul>
472
473<p>Sometimes you may want to create a styled text resource that is also used as a format
474string. Normally, this won't work because the <a
475href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
476java.lang.Object...)">{@code String.format(String, Object...)}</a>
477method will strip all the style
478information from the string. The work-around to this is to write the HTML tags with escaped
479entities, which are then recovered with {@link android.text.Html#fromHtml(String)},
480after the formatting takes place. For example:</p>
481
482<ol>
483 <li>Store your styled text resource as an HTML-escaped string:
484<pre>
485&lt;resources&gt;
486 &lt;string name="welcome_messages"&gt;Hello, %1$s! You have &amp;lt;b>%2$d new messages&amp;lt;/b>.&lt;/string>
487&lt;/resources&gt;
488</pre>
489<p>In this formatted string, a {@code &lt;b>} element is added. Notice that the opening bracket is
490HTML-escaped, using the {@code &amp;lt;} notation.</p>
491 </li>
492 <li>Then format the string as usual, but also call {@link android.text.Html#fromHtml} to
493convert the HTML text into styled text:
494<pre>
495Resources res = {@link android.content.Context#getResources()};
496String text = String.<a
497href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
498java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount);
499CharSequence styledText = Html.fromHtml(text);
500</pre>
501 </li>
502</ol>
503
504<p>Because the {@link android.text.Html#fromHtml} method will format all HTML entities, be sure to
505escape any possible HTML characters in the strings you use with the formatted text, using
506{@link android.text.TextUtils#htmlEncode}. For instance, if you'll be passing a string argument to
507<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
508java.lang.Object...)">{@code String.format()}</a> that may contain characters such as
509"&lt;" or "&amp;", then they must be escaped before formatting, so that when the formatted string
510is passed through {@link android.text.Html#fromHtml}, the characters come out the way they were
511originally written. For example:</p>
512<pre>
513String escapedUsername = TextUtil.{@link android.text.TextUtils#htmlEncode htmlEncode}(username);
514
515Resources res = {@link android.content.Context#getResources()};
516String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
517java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
518CharSequence styledText = Html.fromHtml(text);
519</pre>
520
Robert Ly37cb8d72014-05-08 15:02:11 -0700521<h2 id="StylingWithSpannables">Styling with Spannables</h2>
522<p>
523A {@link android.text.Spannable} is a text object that you can style with
524typeface properties such as color and font weight. You use
525{@link android.text.SpannableStringBuilder} to build
526your text and then apply styles defined in the {@link android.text.style}
527package to the text.
528</p>
Scott Main208b9c52010-02-09 18:48:27 -0800529
Robert Ly37cb8d72014-05-08 15:02:11 -0700530<p>You can use the following helper methods to set up much of the work
531of creating spannable text:</p>
Scott Main208b9c52010-02-09 18:48:27 -0800532
Robert Ly37cb8d72014-05-08 15:02:11 -0700533<pre style="pretty-print">
534/**
535 * Returns a CharSequence that concatenates the specified array of CharSequence
536 * objects and then applies a list of zero or more tags to the entire range.
537 *
538 * @param content an array of character sequences to apply a style to
539 * @param tags the styled span objects to apply to the content
540 * such as android.text.style.StyleSpan
541 *
542 */
543private static CharSequence apply(CharSequence[] content, Object... tags) {
544 SpannableStringBuilder text = new SpannableStringBuilder();
545 openTags(text, tags);
546 for (CharSequence item : content) {
547 text.append(item);
548 }
549 closeTags(text, tags);
550 return text;
551}
552
553/**
554 * Iterates over an array of tags and applies them to the beginning of the specified
555 * Spannable object so that future text appended to the text will have the styling
556 * applied to it. Do not call this method directly.
557 */
558private static void openTags(Spannable text, Object[] tags) {
559 for (Object tag : tags) {
560 text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK);
561 }
562}
563
564/**
565 * "Closes" the specified tags on a Spannable by updating the spans to be
566 * endpoint-exclusive so that future text appended to the end will not take
567 * on the same styling. Do not call this method directly.
568 */
569private static void closeTags(Spannable text, Object[] tags) {
570 int len = text.length();
571 for (Object tag : tags) {
572 if (len > 0) {
573 text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
574 } else {
575 text.removeSpan(tag);
576 }
577 }
578}
579</pre>
580
581<p>
582The following <code>bold</code>, <code>italic</code>, and <code>color</code>
583methods show you how to call the helper methods to apply
584styles defined in the {@link android.text.style} package. You
585can create similar methods to do other types of text styling.
586</p>
587
588<pre style="pretty-print">
589/**
590 * Returns a CharSequence that applies boldface to the concatenation
591 * of the specified CharSequence objects.
592 */
593public static CharSequence bold(CharSequence... content) {
594 return apply(content, new StyleSpan(Typeface.BOLD));
595}
596
597/**
598 * Returns a CharSequence that applies italics to the concatenation
599 * of the specified CharSequence objects.
600 */
601public static CharSequence italic(CharSequence... content) {
602 return apply(content, new StyleSpan(Typeface.ITALIC));
603}
604
605/**
606 * Returns a CharSequence that applies a foreground color to the
607 * concatenation of the specified CharSequence objects.
608 */
609public static CharSequence color(int color, CharSequence... content) {
610 return apply(content, new ForegroundColorSpan(color));
611}
612</pre>
613
614<p>
615Here's an example of how to chain these methods to create a character sequence
616with different types of styling applied to individual words:
617</p>
618
619<pre style="pretty-print">
620// Create an italic "hello, " a red "world",
621// and bold the entire sequence.
622CharSequence text = bold(italic(res.getString(R.string.hello)),
623 color(Color.RED, res.getString(R.string.world)));
Elliott Hughes1fe7d492014-05-23 13:28:33 -0700624</pre>