字符串资源为您的应用提供文本字符串,并可选择文本样式和格式。有三种类型的资源可以为您的应用提供字符串:
所有字符串都可以应用一些样式标记和格式化参数。有关字符串样式和格式的信息,请参阅关于格式化和样式的部分。
字符串
一个可以从应用或其他资源文件(如 XML 布局)引用的单个字符串。
注意:字符串是一种简单资源,通过 name
属性中提供的值(而不是 XML 文件的名称)进行引用。因此,您可以将字符串资源与其他简单资源组合在一个 XML 文件中,置于一个 <resources>
元素下。
- 文件位置
res/values/filename.xml
文件名是任意的。<string>
元素的name
用作资源 ID。- 编译后的资源数据类型
- 指向
String
的资源指针。 - 资源引用
- 在 Java 中:
R.string.string_name
在 XML 中:@string/string_name
- 语法
-
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name" >text_string</string> </resources>
- 元素
- 示例
- XML 文件保存在
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources>
此布局 XML 将字符串应用于 View
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
此应用代码检索字符串
您可以使用
getString(int)
或getText(int)
检索字符串。getText(int)
保留应用于字符串的任何富文本样式。
字符串数组
一个可以从应用引用的字符串数组。
注意:字符串数组是一种简单资源,使用 name
属性中提供的值(而不是 XML 文件的名称)进行引用。因此,您可以将字符串数组资源与其他简单资源组合在一个 XML 文件中,置于一个 <resources>
元素下。
- 文件位置
res/values/filename.xml
文件名是任意的。<string-array>
元素的name
用作资源 ID。- 编译后的资源数据类型
- 指向
String
数组的资源指针。 - 资源引用
- 在 Java 中:
R.array.string_array_name
在 XML 中:@[package:]array/string_array_name
- 语法
-
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item >text_string</item> </string-array> </resources>
- 元素
- 示例
- XML 文件保存在
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>
此应用代码检索字符串数组
Kotlin
val array: Array<String> =
resources
.getStringArray
(R.array.planets_array)Java
Resources res =
getResources()
; String[] planets = res.getStringArray
(R.array.planets_array);
数量字符串(复数)
不同的语言对于数量的语法一致性有不同的规则。例如,在英语中,数量 1 是一个特例。我们写“1 book”,但对于任何其他数量,我们写“n books”。这种单数和复数之间的区别非常常见,但其他语言会做更细致的区分。Android 支持的完整集合是 zero
、one
、two
、few
、many
和 other
。
决定为给定语言和数量使用哪个复数形式的规则可能非常复杂,因此 Android 为您提供了诸如 getQuantityString()
之类的方法,以帮助您选择适当的资源。
虽然历史上称为“数量字符串”(在 API 中仍然如此称呼),但数量字符串应该只用于复数。例如,如果存在未读邮件,使用数量字符串来实现 Gmail 的“收件箱”与“收件箱 (12)”是错误的。使用数量字符串代替 if
语句可能看起来很方便,但需要注意的是,有些语言(如中文)根本不做这些语法区分,因此您总是会得到 other
字符串。
选择使用哪个字符串完全基于语法的必要性。在英语中,即使数量为 0,zero
的字符串也会被忽略,因为 0 在语法上与 2 或除 1 以外的任何其他数字没有区别(“零本书”、“一本书”、“两本书”等等)。相反,在韩语中,只使用 other
字符串。
也不要被诸如 two
听起来好像只适用于数量 2 的事实所误导:一种语言可能要求 2、12、102(等等)都以相同的方式处理,但与其它数量不同。请相信您的翻译人员知道他们的语言实际坚持什么区别。
如果您的消息不包含数量数字,那么它可能不是复数的好选择。例如,在立陶宛语中,单数形式用于 1 和 101,所以“1 book”翻译为“1 knyga”,而“101 books”翻译为“101 knyga”。同时,“a book”是“knyga”,“many books”是“daug knygų”。如果英文复数消息包含“a book”(单数)和“many books”(复数)而没有实际数字,它可以翻译为“knyga”(一本书)/“daug knygų”(许多书),但根据立陶宛语规则,当数字恰好是 101 时,它将显示“knyga”(一本书)。
通常可以通过使用数量中性表述(例如“书籍:1”)来避免使用数量字符串。如果您的应用可以接受这种样式,这将使您和您的翻译人员的工作更加轻松。
在 API 24+ 上,您可以改用功能更强大的 ICU MessageFormat
类。
注意:复数集合是一种简单资源,使用 name
属性中提供的值(而不是 XML 文件的名称)进行引用。因此,您可以将复数资源与其他简单资源组合在一个 XML 文件中,置于一个 <resources>
元素下。
- 文件位置
res/values/filename.xml
文件名是任意的。<plurals>
元素的name
用作资源 ID。- 资源引用
- 在 Java 中:
R.plurals.plural_name
- 语法
-
<?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>
- 元素
- 示例
- XML 文件保存在
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 文件保存在
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>
用法
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);使用
getQuantityString()
方法时,如果您的字符串包含带数字的字符串格式,则需要传递count
两次。例如,对于字符串%d songs found
,第一个count
参数选择适当的复数字符串,第二个count
参数插入到%d
占位符中。如果您的复数字符串不包含字符串格式,则无需向getQuantityString
传递第三个参数。
格式和样式
以下是关于如何正确格式化和设置字符串资源样式的一些重要事项。
处理特殊字符
当字符串包含在 XML 中具有特殊用法的字符时,您必须根据标准 XML/HTML 转义规则转义这些字符。如果您需要转义在 Android 中具有特殊含义的字符,则应使用反斜杠前缀。
默认情况下,Android 会将一系列空白字符折叠成一个空格。您可以通过将字符串的相关部分用双引号括起来来避免这种情况。在这种情况下,所有空白字符(包括换行符)都将保留在带引号的区域内。双引号还允许您使用常规的未转义单引号。
字符 | 转义形式 |
---|---|
@ | \@ |
? | \? |
换行符 | \n |
制表符 | \t |
U+XXXX Unicode 字符 | \uXXXX |
单引号 (' ) |
以下任意一种
|
双引号 (" ) |
\"
请注意,用单引号括起来的字符串不起作用。 |
在资源文件被解析为 XML 后,空白折叠和 Android 转义会发生。这意味着 <string>      </string>
(空格、标点空格、Unicode Em 空格)在文件被解析为 XML 后都将折叠成一个空格(" "
)。为了保留这些空格,您可以将其用引号括起来(<string>"      "</string>
)或使用 Android 转义(<string> \u0032 \u8200 \u8195</string>
)。
注意:从 XML 解析器的角度来看,<string>"Test this"</string>
和 <string>"Test this"</string>
之间没有区别。两种形式都不会显示任何引号,但会触发 Android 保留空白的引号(在这种情况下没有实际效果)。
格式化字符串
如果您需要格式化字符串,则可以将格式参数放在字符串资源中,如下面的示例资源所示。
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
在此示例中,格式字符串有两个参数:%1$s
是一个字符串,%2$d
是一个十进制数字。然后,通过调用 getString(int, Object...)
来格式化字符串。例如:
Kotlin
var text = getString(R.string.welcome_messages, username, mailCount)
Java
String text = getString(R.string.welcome_messages, username, mailCount);
使用 HTML 标记进行样式设置
您可以使用 HTML 标记为字符串添加样式。例如:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="welcome">Welcome to <b>Android</b>!</string> </resources>
支持以下 HTML 元素:
- 粗体:<b>
- 斜体:<i>、<cite>、<dfn>、<em>
- 增大 25% 的文本:<big>
- 缩小 20% 的文本:<small>
- 设置字体属性:<font face=”font_family“ color=”hex_color”>。可能的字体系列示例包括
monospace
、serif
和sans_serif
。 - 设置等宽字体系列:<tt>
- 删除线:<s>、<strike>、<del>
- 下划线:<u>
- 上标:<sup>
- 下标:<sub>
- 项目符号:<ul>、<li>
- 换行:<br>
- 分区:<div>
- CSS 样式:<span style=”color|background_color|text-decoration”>
- 段落:<p dir=”rtl | ltr” style=”…”>
如果您不应用格式,可以直接通过调用 setText(java.lang.CharSequence)
来设置 TextView 文本。然而,在某些情况下,您可能希望创建一个也用作格式字符串的样式文本资源。通常,这不起作用,因为 format(String, Object...)
和 getString(int, Object...)
方法会从字符串中剥离所有样式信息。解决方法是使用转义实体编写 HTML 标签,然后在格式化发生后,使用 fromHtml(String)
恢复它们。例如:
- 将您的样式文本资源存储为 HTML 转义字符串
<resources> <string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string> </resources>
在此格式化字符串中,添加了
<b>
元素。请注意,左尖括号使用<
符号进行了 HTML 转义。 - 然后像往常一样格式化字符串,但也调用
fromHtml(String)
将 HTML 文本转换为样式文本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);
由于 fromHtml(String)
方法会格式化所有 HTML 实体,因此请确保使用 htmlEncode(String)
转义您用于格式化文本的字符串中任何可能的 HTML 字符。例如,如果您要格式化一个包含“<”或“&”等字符的字符串,则必须在格式化之前将其转义,以便在格式化后的字符串通过 fromHtml(String)
时,这些字符以它们最初写入的方式出现。例如:
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);
使用 Spannable 进行样式设置
一个 Spannable
是一个文本对象,您可以使用字体属性(如颜色和字体粗细)对其进行样式设置。您可以使用 SpannableStringBuilder
构建文本,然后将 android.text.style
包中定义的样式应用于文本。
您可以使用以下辅助方法来完成创建可跨越文本的大部分工作:
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<out CharSequence>, 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<out Any>) { 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<out Any>) { 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); } } }
以下 bold
、italic
和 color
方法封装了上述辅助方法,并演示了应用 android.text.style
包中定义的样式的具体示例。您可以创建类似的方法来执行其他类型的文本样式设置。
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)); }
这是一个如何将这些方法串联起来,以对短语中的单个单词应用各种样式的示例:
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)));
core-ktx Kotlin 模块还包含扩展函数,使处理 spans 变得更加容易。您可以查看 GitHub 上的 android.text 包文档以了解更多信息。
有关使用 span 的更多信息,请参阅以下链接:
使用注解进行样式设置
您可以使用 Annotation
类以及 strings.xml 资源文件中的 <annotation>
标记来应用复杂或自定义样式。annotation 标记允许您通过在 XML 中定义自定义键值对来标记字符串的部分以进行自定义样式设置,框架随后会将其转换为 Annotation
span。然后,您可以检索这些注解并使用键和值来应用样式。
创建注解时,请确保在所有 strings.xml 文件中将 <annotation>
标记添加到字符串的所有翻译中。
在所有语言中将自定义字体应用于“文本”一词
示例 - 添加自定义字体
-
添加
<annotation>
标签,并定义键值对。在此示例中,键是 font,值是我们想要使用的字体类型:title_emphasis// values/strings.xml <string name="title">Best practices for <annotation font="title_emphasis">text</annotation> on Android</string> // values-es/strings.xml <string name="title"><annotation font="title_emphasis">Texto</annotation> en Android: mejores prácticas</string>
-
加载字符串资源并找到带有 font 键的注解。然后创建自定义 span 并替换现有 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 = spannableString
Java
// 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;
如果您多次使用相同的文本,您应该只构建一次 SpannableString 对象并根据需要重用它,以避免潜在的性能和内存问题。
有关注解用法的更多示例,请参阅 Android 中的国际化文本样式
注解 span 和文本 Parceling
由于 Annotation
span 也是 ParcelableSpans
,因此键值对会被 parcel 和 unparcel。只要 parcel 的接收者知道如何解释注解,您就可以使用 Annotation
span 将自定义样式应用于 parcel 后的文本。
要在将文本传递到 Intent Bundle 时保留自定义样式,您首先需要向文本添加 Annotation
span。您可以通过 XML 资源中的 <annotation> 标签(如上例所示)或通过代码创建新的 Annotation
并将其设置为 span(如下所示)来完成此操作
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);
从 Bundle
中以 SpannableString
形式检索文本,然后解析附加的注解,如上例所示。
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);
有关文本样式的更多信息,请参阅以下链接: