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.
- 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.
- 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.
- 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>).
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 "<" or "&" val escapedUsername = TextUtils.htmlEncode(username) val text = stringResource( R.string.welcome_messages, escapedUsername, mailCount, ) Text( text = AnnotatedString.fromHtml(text) ) }
Styling with AnnotatedString
An AnnotatedString is a Compose text object that you can style with
properties such as color and font weight. Build styled text programmatically
using buildAnnotatedString and withStyle.
This application code creates a single text element with mixed styles:
@Composable fun StyledGreeting() { val styled = buildAnnotatedString { append("Welcome to ") withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append("Android") } append("!") } Text(text = styled) }
To apply color, font size, and text decoration, use SpanStyle. To apply
paragraph-level styling (like alignment or line height), use ParagraphStyle:
@Composable fun RichText() { val text = buildAnnotatedString { withStyle(ParagraphStyle(lineHeight = 24.sp, textAlign = TextAlign.Center)) { withStyle(SpanStyle(color = Color.Gray)) { append("Hello, ") } withStyle( SpanStyle( fontWeight = FontWeight.Bold, color = Color.Red, ) ) { append("world") } append("!") } } Text(text = text) }
Building the AnnotatedString directly is the recommended approach for
single-language apps or static text in Compose. However, for styled text that
requires localization, see the XML <annotation> approach detailed in the next
section.
Styling translated strings with annotations
For strings that need custom styling and translation, define the
<annotation> tag in each locale's strings.xml. Translators preserve the
annotation regardless of where it lands in the sentence. Read the string with
context.resources.getText(), walk its Annotation spans, and convert the
result into an AnnotatedString:
@Composable fun AnnotatedTitle() { val context = LocalContext.current val source = context.resources.getText(R.string.title) as SpannedString val text = buildAnnotatedString { append(source.toString()) source.getSpans(0, source.length, Annotation::class.java) .forEach { annotation -> if (annotation.key == "font" && annotation.value == "title_emphasis") { addStyle( SpanStyle( fontFamily = FontFamily( Font(R.font.permanent_marker) ) ), source.getSpanStart(annotation), source.getSpanEnd(annotation), ) } } } Text(text = text) }
The <annotation> tag in your XML is unchanged. Only the retrieval code
differs. Translators still move the tag to wrap the correct word in each
language.
Additional resources
For more information about string resources, see the following additional resources: