A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:
- String
- XML resource that provides a single string.
- String Array
- XML resource that provides an array of strings.
- Quantity Strings (Plurals)
- XML resource that carries different strings for pluralization.
All strings are capable of applying some styling markup and formatting arguments. For information about styling and formatting strings, see the section about Formatting and Styling.
String
A single string that can be referenced from the application code (such as a composable function) or from other resource files.
Note: A string is a simple resource that is referenced using the value provided in thename attribute (not the name of the XML file). So, you can combine
string resources with other simple resources in the one XML file, under one
<resources> element.
- file location:
res/values/filename.xml
The filename is arbitrary. The<string>element'snameis used as the resource ID.- compiled resource datatype:
- Resource pointer to a
String. - resource reference:
-
In Kotlin:
R.string.string_name
In XML:@string/string_name - syntax:
-
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name" >text_string</string> </resources>
- elements:
- example:
- XML file saved at
res/values/strings.xml:<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources>
This application code retrieves a string from inside a composable with
stringResource():@Composable fun Greeting() { Text(text = stringResource(R.string.hello)) }
Note: To retrieve a string outside of a composable function, use
You can also reference string resources from other XML files, such as yourcontext.getString(R.string.hello).AndroidManifest.xml:<activity android:name=".MainActivity" android:label="@string/hello" />
String array
An array of strings that can be referenced from the application.
Note: A string array is a simple resource that is referenced using the value provided in thename attribute (not the name of the XML file). As such, you
can combine string array resources with other simple resources in the one XML
file, under one <resources> element.
- file location:
res/values/filename.xml
The filename is arbitrary. The<string-array>element'snameis used as the resource ID.- compiled resource datatype:
- Resource pointer to an array of
Strings. - resource reference:
-
In Kotlin:
R.array.string_array_name
In XML:@[package:]array/string_array_name - syntax:
-
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item >text_string</item> </string-array> </resources>
- elements:
- example:
- XML file saved at
res/values/strings.xml:<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> </string-array> </resources>
This application code retrieves a string array from inside a composable with
stringArrayResource():@Composable fun PlanetList() { val planets: Array = stringArrayResource(R.array.planets_array) // Render the array, e.g. inside a LazyColumn. }
Note: To retrieve a string array outside of a composable function, use
context.resources.getStringArray(R.array.planets_array).
Quantity strings (plurals)
Different languages have different rules for grammatical agreement with
quantity. In English, for example, the quantity 1 is a special case. We write
"1 book", but for any other quantity we'd write "n books". This distinction
between singular and plural is very common, but other languages make finer
distinctions. The full set supported by Android is zero, one, two, few,
many, and other.
The rules for deciding which case to use for a given language and quantity can
be very complex, so Android provides you with methods such as
pluralStringResource() to select the appropriate resource for you.
Although historically called "quantity strings" (and still called that in API),
quantity strings should only be used for plurals. It would be a mistake to
use quantity strings to implement something like Gmail's "Inbox" versus
"Inbox (12)" when there are unread messages, for example. It might seem
convenient to use quantity strings instead of an if statement, but it's
important to note that some languages (such as Chinese) don't make these
grammatical distinctions at all, so you'll always get the other string.
The selection of which string to use is made solely based on grammatical
necessity. In English, a string for zero is ignored even if the quantity is
0, because 0 isn't grammatically different from 2, or any other number except 1
("zero books", "one book", "two books", and so on). Conversely, in Korean
only the other string is ever used.
Don't be misled either by the fact that, say, two sounds like it could only
apply to the quantity 2: a language may require that 2, 12, 102 (and so on) are
all treated like one another but differently to other quantities. Rely on your
translator to know what distinctions their language actually insists upon.
If your message doesn't contain the quantity number, it is probably not a good candidate for a plural. For example, in Lithuanian the singular form is used for both 1 and 101, so "1 book" is translated as "1 knyga", and "101 books" is translated as "101 knyga". Meanwhile "a book" is "knyga" and "many books" is "daug knyg". If an English plural message contains "a book" (singular) and "many books" (plural) without the actual number, it can be translated as "knyga" (a book)/"daug knyg" (many books), but with Lithuanian rules, it will show "knyga" (a single book), when the number happens to be 101.
It's often possible to avoid quantity strings by using quantity-neutral formulations such as "Books: 1". This makes your life and your translators' lives easier, if it's an acceptable style for your application.
On API 24+ you can use the much more powerful ICU MessageFormat
class instead.
name attribute (not the name of the XML file). As such
you can combine plurals resources with other simple resources in the one XML
file, under one <resources> element.
- file location:
res/values/filename.xml
The filename is arbitrary. The<plurals>element'snameis used as the resource ID.- resource reference:
-
In Kotlin:
R.plurals.plural_name - syntax:
-
<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="plural_name"> <item quantity=["zero" | "one" | "two" | "few" | "many" | "other"] >text_string</item> </plurals> </resources>
- elements:
- example:
XML file saved at
res/values/strings.xml:<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="numberOfSongsAvailable"> <!-- As a developer, you should always supply "one" and "other" strings. Your translators will know which strings are actually needed for their language. Always include %d in "one" because translators will need to use %d for languages where "one" doesn't mean 1 (as explained above). --> <item quantity="one">%d song found.</item> <item quantity="other">%d songs found.</item> </plurals> </resources>
XML file saved at
res/values-pl/strings.xml:<?xml version="1.0" encoding="utf-8"?> <resources> <plurals name="numberOfSongsAvailable"> <item quantity="one">Znaleziono %d piosenkę.</item> <item quantity="few">Znaleziono %d piosenki.</item> <item quantity="other">Znaleziono %d piosenek.</item> </plurals> </resources>
This application code retrieves a plural string from inside a composable with
pluralStringResource():@Composable fun SongCount(count: Int) { Text( text = pluralStringResource( R.plurals.numberOfSongsAvailable, count, count, ) ) }
When using the
pluralStringResource()function, you need to pass thecounttwice if your string includes string formatting with a number. For example, for the string%d songs found, the firstcountparameter selects the appropriate plural string and the secondcountparameter is inserted into the%dplaceholder. If your plural strings do not include string formatting, you don't need to pass the third parameter topluralStringResource.Note: To retrieve a plural string outside of a composable function, use
context.resources.getQuantityString(R.plurals.numberOfSongsAvailable, count, count).
Format and style
Here are a few important things you should know about how to properly format and style your string resources.
Handle special characters
When a string contains characters that have special usage in XML, you must escape the characters according to the standard XML/HTML escaping rules. If you need to escape a character that has special meaning in Android you should use a preceding backslash.
By default Android will collapse sequences of whitespace characters into a single space. You can avoid this by enclosing the relevant part of your string in double quotes. In this case all whitespace characters (including new lines) will get preserved within the quoted region. Double quotes will allow you to use regular single unescaped quotes as well.
| Character | Escaped form(s) |
|---|---|
| @ | \@ |
| ? | \? |
| New line | \n |
| Tab | \t |
| U+XXXX Unicode character | \uXXXX |
Single quote (') |
Any of the following:
|
Double quote (") |
\"
Note that surrounding the string with single quotes does not work. |
Whitespace collapsing and Android escaping happen after your resource file
gets parsed as XML. This means that <string>      </string>
(space, punctuation space, Unicode Em space) all collapse to a single space
(" "), because they are all Unicode spaces after the file is parsed as an XML.
To preserve those spaces as they are, you can either quote them
(<string>"      "</string>)
or use Android escaping
(<string> \u0032 \u8200 \u8195</string>).
<string>"Test this"</string> and
<string>&quot;Test this&quot;</string> whatsoever. Both forms will
not show any quotes but trigger Android whitespace-preserving quoting (that
will have no practical effect in this case).
Formatting strings
If you need to format your strings, then you can do so by putting your format arguments in the string resource, as demonstrated by the following example resource.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
This application code formats the string from inside a composable by passing
arguments directly into stringResource():
@Composable fun WelcomeMessage(username: String, mailCount: Int) { Text( text = stringResource( R.string.welcome_messages, username, mailCount, ) ) }
Styling with HTML markup
You can add styling to your strings with HTML markup. For example:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="welcome">Welcome to <b>Android</b>!</string> </resources>
The following HTML elements are supported:
- Bold:
<b> - Italic:
<i>,<cite>,<dfn>,<em> - 25% larger text:
<big> - 20% smaller text:
<small> - Setting font properties:
<font face="font_family" color="hex_color">. Examples of possible font families includemonospace,serif, andsans_serif. - Setting a monospace font family:
<tt> - Strikethrough:
<s>,<strike>,<del> - Underline:
<u> - Superscript:
<sup> - Subscript:
<sub> - Bullet points:
<ul>,<li> - Line breaks:
<br> - Division:
<div> - CSS style:
<span style="color|background_color|text-decoration"> - Paragraphs:
<p dir="rtl | ltr" style="">
In some cases, you may want to create a styled text resource that is also used
as a format string. Normally, this doesn't work because formatting methods,
such as stringResource(), strip all the style information from the string.
The work-around to this is to write the HTML tags with escaped entities, which
are then recovered with AnnotatedString.fromHtml(), after the formatting
takes place. For example:
- Store your styled text resource as an HTML-escaped string:
<resources> <string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string> </resources>
In this formatted string, a
<b>element is added. Notice that the opening bracket is HTML-escaped, using the<notation. - Then format the string as usual, but also call
AnnotatedString.fromHtml()to convert the HTML text into a styled Compose string.
Because fromHtml() formats all HTML entities, be sure to escape any possible
HTML characters in the strings you use with the formatted text, using
TextUtils.htmlEncode().
import android.text.TextUtils import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.fromHtml @Composable fun WelcomeHtmlMessage(username: String, mailCount: Int) { // Escape the username in case it contains characters like "
Web Proxy Viewer | New URL | Original Page