String resources | Android Developers
- 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 .
Mục Chính
String
A single string that can be referenced from the application or from other resource files ( such as an XML layout ) .
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 oneelement.
Bạn đang đọc: String resources | Android Developers
- file location:
res/values/filename.xml
The filename is arbitrary. Theelement’s
name
is used as the
resource ID.- compiled resource datatype:
- Resource pointer to a
String
.- resource reference:
- In Java:
R.string.string_name
In XML:@string/string_name
- syntax:
text_string - elements:
- example:
- XML file saved at
res/values/strings.xml
:Hello! This layout XML applies a string to a View :
android:text="@string/hello" /> This application code retrieves a string :
Kotlin
val string: String =getString
(R.string.hello)Java
String string =getString
(R.string.hello);You can use either
getString(int)
or
getText(int)
to retrieve a string.getText(int)
retains any rich text styling applied to the string.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 oneelement.
- file location:
res/values/filename.xml
The filename is arbitrary. Theelement’s
name
is used as the
resource ID.- compiled resource datatype:
- Resource pointer to an array of
String
s.- resource reference:
- In Java:
R.array.string_array_name
In XML:@[package:]array/string_array_name
- syntax:
- text_string
- elements:
- example:
- XML file saved at
res/values/strings.xml
:- Mercury
- Venus
- Earth
- Mars
This application code retrieves a string array :
Kotlin
val array: Array= resources
.getStringArray
(R.array.planets_array)Java
Resources res =getResources()
; String[] planets = res.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 iszero
,
one
,two
,few
,many
, andother
.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
getQuantityString()
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 anif
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 theother
string.The selection of which string to use is made solely based on grammatical necessity.
In English, a string forzero
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 theother
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.Note: A plurals collection 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 plurals resources with other simple resources in the one
XML file, under oneelement.
- file location:
res/values/filename.xml
The filename is arbitrary. Theelement’s
name
is used as the
resource ID.- resource reference:
- In Java:
R.plurals.plural_name
- syntax:
- text_string
- elements:
- example:
- XML file saved at
res/values/strings.xml
:- %d song found.
- %d songs found.
XML file saved at
res/values-pl/strings.xml
:- Znaleziono %d piosenkę.
- Znaleziono %d piosenki.
- Znaleziono %d piosenek.
Usage :
Kotlin
val count = getNumberOfSongsAvailable() val songsFound = resources.getQuantityString
(R.plurals.numberOfSongsAvailable, count, count)Java
int count = getNumberOfSongsAvailable(); Resources res =getResources()
; String songsFound = res.getQuantityString
(R.plurals.numberOfSongsAvailable, count, count);When using the
getQuantityString()
method, you need to pass thecount
twice if your string includes
string formatting with a number. For example, for the string
%d songs found
, the firstcount
parameter selects the appropriate plural string and
the secondcount
parameter is inserted into the%d
placeholder. If your plural
strings do not include string formatting, you don’t need to pass the third parameter togetQuantityString
.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.Xem thêm: Định vị xe máy BK88M
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 :
\'
- Enclose the entire string in double quotes
("This'll work"
, for example)Double quote ( "
)\"
Note that surrounding the string with single quotes does not work .Whitespace collapsing and Android escaping happens after your
resource file gets parsed as XML. This means that
(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
()
" "
or use Android escaping
().
\u0032 \u8200 \u8195 Note: From XML parser’s perspective, there is no difference between
and
"Test this"
whatsoever. Both forms
"Test this"
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 .
Hello, %1$s! You have %2$d new messages. In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal number. Then, format the string by callinggetString(int, Object...)
. For example:Kotlin
var text = getString(R.string.welcome_messages, username, mailCount)Java
String text = getString(R.string.welcome_messages, username, mailCount);Styling with HTML markup
You can add styling to your strings with HTML markup. For example :
Welcome to Android! The following HTML elements are supported :
- Bold: ,
- Italic: , ,
- 25% larger text:
- 20% smaller text:
- Setting font properties: . Examples of
possible font families includemonospace
,serif
, and
sans_serif
.- Setting a monospace font family:
- Strikethrough:
,,- Underline:
- Superscript:
- Subscript:
- Bullet points:
,
- Line breaks:
- Division:
- CSS style:
- Paragraphs:
If you aren’t applying formatting, you can set TextView text directly by calling
setText(java.lang.CharSequence)
. In some cases, however, you may
want to create a styled text resource that is also used as a format string. Normally, this
doesn’t work because theformat(String, Object...)
and
getString(int, Object...)
methods 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 withfromHtml(String)
,
after the formatting takes place. For example:
- Store your styled text resource as an HTML-escaped string:
Hello, %1$s! You have %2$d new messages. In this formatted string, a
element is added. Notice that the opening bracket is
HTML-escaped, using the<
notation.- Then format the string as usual, but also call
fromHtml(String)
to
convert the HTML text into styled text:Kotlin
val text: String = getString(R.string.welcome_messages, username, mailCount) val styledText: Spanned = Html.fromHtml(text, FROM_HTML_MODE_LEGACY)Java
String text = getString(R.string.welcome_messages, username, mailCount); Spanned styledText = Html.fromHtml(text, FROM_HTML_MODE_LEGACY);Because the
fromHtml(String)
method formats all HTML entities, be sure to
escape any possible HTML characters in the strings you use with the formatted text, using
htmlEncode(String)
. For instance, if you are formatting a string that contains characters such as
"<" or "&", then they must be escaped before formatting, so that when the formatted string is passed throughfromHtml(String)
, the characters come out the way they were
originally written. For example:Kotlin
val escapedUsername: String = TextUtils.htmlEncode
(username) val text: String = getString(R.string.welcome_messages, escapedUsername, mailCount) val styledText: Spanned = Html.fromHtml(text, FROM_HTML_MODE_LEGACY)Java
String escapedUsername = TextUtils.htmlEncode
(username); String text = getString(R.string.welcome_messages, escapedUsername, mailCount); Spanned styledText = Html.fromHtml(text);Styling with spannables
A
Spannable
is a text object that you can style with
typeface properties such as color and font weight. You use
SpannableStringBuilder
to build
your text and then apply styles defined in theandroid.text.style
package to the text.You can use the following helper methods to set up much of the work of creating spannable text :
Kotlin
/** * Returns a CharSequence that concatenates the specified array of CharSequence * objects and then applies a list of zero or more tags to the entire range. * * @param content an array of character sequences to apply a style to * @param tags the styled span objects to apply to the content * such as android.text.style.StyleSpan */ private fun apply(content: Array, vararg tags: Any): CharSequence { return SpannableStringBuilder().apply { openTags(tags) content.forEach { charSequence -> append(charSequence) } closeTags(tags) } } /** * Iterates over an array of tags and applies them to the beginning of the specified * Spannable object so that future text appended to the text will have the styling * applied to it. Do not call this method directly. */ private fun Spannable.openTags(tags: Array ) { tags.forEach { tag -> setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK) } } /** * "Closes" the specified tags on a Spannable by updating the spans to be * endpoint-exclusive so that future text appended to the end will not take * on the same styling. Do not call this method directly. */ private fun Spannable.closeTags(tags: Array ) { tags.forEach { tag -> if (length > 0) { setSpan(tag, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } else { removeSpan(tag) } } } Java
/** * Returns a CharSequence that concatenates the specified array of CharSequence * objects and then applies a list of zero or more tags to the entire range. * * @param content an array of character sequences to apply a style to * @param tags the styled span objects to apply to the content * such as android.text.style.StyleSpan * */ private static CharSequence applyStyles(CharSequence[] content, Object[] tags) { SpannableStringBuilder text = new SpannableStringBuilder(); openTags(text, tags); for (CharSequence item : content) { text.append(item); } closeTags(text, tags); return text; } /** * Iterates over an array of tags and applies them to the beginning of the specified * Spannable object so that future text appended to the text will have the styling * applied to it. Do not call this method directly. */ private static void openTags(Spannable text, Object[] tags) { for (Object tag : tags) { text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK); } } /** * "Closes" the specified tags on a Spannable by updating the spans to be * endpoint-exclusive so that future text appended to the end will not take * on the same styling. Do not call this method directly. */ private static void closeTags(Spannable text, Object[] tags) { int len = text.length(); for (Object tag : tags) { if (len > 0) { text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { text.removeSpan(tag); } } }The following
bold
,italic
, andcolor
methods wrap the helper methods above and demonstrate specific examples of applying
styles defined in theandroid.text.style
package. You
can create similar methods to do other types of text styling.Kotlin
/** * Returns a CharSequence that applies boldface to the concatenation * of the specified CharSequence objects. */ fun bold(vararg content: CharSequence): CharSequence = apply(content, StyleSpan(Typeface.BOLD)) /** * Returns a CharSequence that applies italics to the concatenation * of the specified CharSequence objects. */ fun italic(vararg content: CharSequence): CharSequence = apply(content, StyleSpan(Typeface.ITALIC)) /** * Returns a CharSequence that applies a foreground color to the * concatenation of the specified CharSequence objects. */ fun color(color: Int, vararg content: CharSequence): CharSequence = apply(content, ForegroundColorSpan(color))Java
/** * Returns a CharSequence that applies boldface to the concatenation * of the specified CharSequence objects. */ public static CharSequence bold(CharSequence... content) { return apply(content, new StyleSpan(Typeface.BOLD)); } /** * Returns a CharSequence that applies italics to the concatenation * of the specified CharSequence objects. */ public static CharSequence italic(CharSequence... content) { return apply(content, new StyleSpan(Typeface.ITALIC)); } /** * Returns a CharSequence that applies a foreground color to the * concatenation of the specified CharSequence objects. */ public static CharSequence color(int color, CharSequence... content) { return apply(content, new ForegroundColorSpan(color)); }Here’s an example of how to chain these methods together to apply various styles to individual words within a phrase :
Kotlin
// Create an italic "hello, " a red "world", // and bold the entire sequence. val text: CharSequence = bold(italic(getString(R.string.hello)), color(Color.RED, getString(R.string.world)))Java
// Create an italic "hello, " a red "world", // and bold the entire sequence. CharSequence text = bold(italic(getString(R.string.hello)), color(Color.RED, getString(R.string.world)));The core-ktx Kotlin module also contains extension functions that make working with spans even easier. You can check out the android.text package documentation on GitHub to learn more .
For more information on working with spans, see the following link :Styling with annotations
You can apply complex or custom styling by using the
Annotation
class along with the
tag in your strings.xml resource files. The annotation tag allows
you to mark parts of the string for custom styling by defining custom key-value pairs in the XML
that the framework then converts intoAnnotation
spans. You can then retrieve these
annotations and use the key and value to apply the styling.When creating annotations, make sure you add the
tag to all translations of the string in every strings.xml file.
Applying a custom typeface to the word “text” in all languagesExample – adding a custom typeface
Add the
tag, and define the key-value pair. In this case, the
key is font, and the value is the type of font we want to use: title_emphasis// values/strings.xmlBest practices for // values-es/strings.xmltext on AndroidTexto en Android: mejores prácticasLoad the string resource and find the annotations with the font key. Then create a
custom span and replace the existing span.Kotlin
// get the text as SpannedString so we can get the spans attached to the text val titleText = getText(R.string.title) as SpannedString // get all the annotation spans from the text val annotations = titleText.getSpans(0, titleText.length, Annotation::class.java) // create a copy of the title text as a SpannableString. // the constructor copies both the text and the spans. so we can add and remove spans val spannableString = SpannableString(titleText) // iterate through all the annotation spans for (annotation in annotations) { // look for the span with the key font if (annotation.key == "font") { val fontName = annotation.value // check the value associated to the annotation key if (fontName == "title_emphasis") { // create the typeface val typeface = getFontCompat(R.font.permanent_marker) // set the span at the same indices as the annotation spannableString.setSpan(CustomTypefaceSpan(typeface), titleText.getSpanStart(annotation), titleText.getSpanEnd(annotation), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } // now, the spannableString contains both the annotation spans and the CustomTypefaceSpan styledText.text = spannableStringJava
// get the text as SpannedString so we can get the spans attached to the text SpannedString titleText = (SpannedString) getText(R.string.title); // get all the annotation spans from the text Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class); // create a copy of the title text as a SpannableString. // the constructor copies both the text and the spans. so we can add and remove spans SpannableString spannableString = new SpannableString(titleText); // iterate through all the annotation spans for (Annotation annotation: annotations) { // look for the span with the key font if (annotation.getKey().equals("font")) { String fontName = annotation.getValue(); // check the value associated to the annotation key if (fontName.equals("title_emphasis")) { // create the typeface Typeface typeface = ResourcesCompat.getFont(this, R.font.roboto_mono); // set the span at the same indices as the annotation spannableString.setSpan(new CustomTypefaceSpan(typeface), titleText.getSpanStart(annotation), titleText.getSpanEnd(annotation), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } // now, the spannableString contains both the annotation spans and the CustomTypefaceSpan styledText.text = spannableString;If you’re using the same text multiple times, you should construct the SpannableString object once and reuse it as needed to avoid potential performance and memory issues .
For more examples of annotation usage, see Styling internationalized text in AndroidAnnotation spans and text parceling
Because
Annotation
spans are alsoParcelableSpans
, the key-value
pairs are parceled and unparceled. As long as the receiver of the parcel knows how to interpret
the annotations, you can useAnnotation
spans to apply custom styling to the
parceled text.To keep your custom styling when you pass the text to an Intent Bundle, you first need to add
Annotation
spans to your text. You can do this in the XML resources via the
tag, as shown in the example above, or in code by creating a new
Annotation
and setting it as a span, as shown below:Kotlin
val spannableString = SpannableString("My spantastic text") val annotation = Annotation("font", "title_emphasis") spannableString.setSpan(annotation, 3, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) // start Activity with text with spans val intent = Intent(this, MainActivity::class.java) intent.putExtra(TEXT_EXTRA, spannableString) startActivity(intent)Java
SpannableString spannableString = new SpannableString("My spantastic text"); Annotation annotation = new Annotation("font", "title_emphasis"); spannableString.setSpan(annotation, 3, 7, 33); // start Activity with text with spans Intent intent = new Intent(this, MainActivity.class); intent.putExtra(TEXT_EXTRA, spannableString); this.startActivity(intent);Retrieve the text from the
Bundle
as aSpannableString
and then parse
the annotations attached, as shown in the example above.
Kotlin
// read text with Spans val intentCharSequence = intent.getCharSequenceExtra(TEXT_EXTRA) as SpannableString
Java
// read text with Spans SpannableString intentCharSequence = (SpannableString)intent.getCharSequenceExtra(TEXT_EXTRA);
For more information on text styling, see the following link :
Source: https://thomaygiat.com
Category : Ứng Dụng
Máy Giặt Electrolux Lỗi E51 Làm Tăng Nguy Cơ Hỏng Nặng
Mục ChínhMáy Giặt Electrolux Lỗi E51 Làm Tăng Nguy Cơ Hỏng NặngNguyên Nhân Máy Giặt Electrolux Báo Lỗi E511. Động Cơ Hỏng2. Mạch Điều Khiển…
Hậu quả từ lỗi H-29 tủ lạnh Sharp Side by Side
Mục ChínhHậu quả từ lỗi H-29 tủ lạnh Sharp Side by SideMã Lỗi H-29 Tủ Lạnh Sharp Là Gì?Tầm Quan Trọng Của Việc Khắc Phục…
Hỏi đáp giấy dán tường chống ẩm mốc
Mục ChínhGiải Mã 25+ Hỏi Đáp Giấy Dán Tường Chống Ẩm MốcChống ẩm mốc cùng giấy dán tường1. Nguyên nhân gây ẩm mốc trong không…
Máy Giặt Electrolux Lỗi E-45 Kiểm Tra Ngay!
Mục ChínhMáy Giặt Electrolux Lỗi E-45 Kiểm Tra Ngay!Định Nghĩa Mã Lỗi E-45 Máy Giặt ElectroluxNguyên nhân lỗi E-45 máy giặt Electrolux1. Cảm biến cửa…
Hướng dẫn sửa Tủ lạnh Sharp lỗi H-28 chi tiết và an toàn
Mục ChínhHướng dẫn sửa Tủ lạnh Sharp lỗi H-28 chi tiết và an toànLỗi H-28 Trên Tủ Lạnh Sharp Là Gì?Dấu Hiệu Nhận Biết Lỗi…
Máy giặt Electrolux gặp lỗi E-44 điều bạn nên làm
Mục ChínhMáy giặt Electrolux gặp lỗi E-44 điều bạn nên làmĐịnh nghĩa mã lỗi E-44 máy giặt Electrolux5 Nguyên nhân gây ra mã lỗi E-44…