字符串资源(视图)

概念和 Jetpack Compose 实现

字符串资源用于为应用提供具有可选文本样式和格式设置的文本字符串。有三种类型的资源可为应用提供字符串:

String
提供单个字符串的 XML 资源。
字符串数组
提供字符串数组的 XML 资源。
数量字符串(复数)
XML 资源,包含各种复数形式的字符串。

所有字符串都能应用某些样式设置标记和格式设置参数。如需了解有关样式和格式设置字符串的信息,请参阅 格式和样式设置部分。

String

可从应用或其他资源文件(如 XML 布局)引用的单个字符串。

文件位置:
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>
元素:
<resources>
必需。该元素必须是根节点。

无属性。

<string>
字符串,可包含样式设置标记。请注意,您必须对撇号和引号进行转义。如需了解有关如何正确设置字符串样式和格式的详细信息,请参阅下文的格式和样式设置

属性:

name
字符串。字符串的名称。此名称用作资源 ID。
示例:
保存在 res/values/strings.xml 的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>

该布局 XML 会对视图应用一个字符串:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

以下应用代码用于检索字符串:

Kotlin

val string: String = getString(R.string.hello)

Java

String string = getString(R.string.hello);

您可以使用 getString(int)getText(int) 检索字符串。 会保留所有应用于字符串的富文本样式。getText(int) 会保留所有应用于字符串的富文本样式。

字符串数组

可从应用引用的字符串数组。

文件位置:
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>
元素:
<resources>
必需。该元素必须是根节点。

无属性。

<string-array>
定义一个字符串数组。包含一个或多个 <item> 元素。

属性:

name
字符串。数组的名称。此名称用作引用数组的资源 ID。
<item>
字符串,可包含样式设置标记。该值可以是对另一个字符串资源的引用。必须为 <string-array> 元素的子项。请注意,您必须对撇号和引号进行转义。如需了解有关如何正确设置字符串样式和格式的信息,请参阅下文的格式和样式设置

无属性。

示例:
保存在 res/values/strings.xml 的 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 支持的完整集为 zeroonetwofewmanyother

决定为给定语言和数量使用哪种情况的规则可能非常复杂,因此 Android 为您提供 诸如 getQuantityString() 等方法来选择合适资源。

在 API 24 及更高版本中,您可以使用功能更强大的 ICU MessageFormat 类。

文件位置:
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>
元素:
<resources>
必需。该元素必须是根节点。

无属性。

<plurals>
字符串集合,根据事物数量提供其中的一个字符串。包含一个或多个 <item> 元素。

属性:

name
字符串。字符串对的名称。此名称用作资源 ID。
</dd>

<item>
一个复数或单数字符串。该值可以是对另一个字符串资源的引用。必须为 <plurals> 元素的子项。请注意,您必须对撇号和引号进行转义。如需了解有关如何正确设置字符串样式和格式的信息,请参阅下文的格式和 样式设置

属性:

quantity
关键字。表示应在何时使用该字符串的值。以下是该关键字的有效值(括号内仅为部分示例):
说明
zero当某种语言要求对数字 0(如阿拉伯语中的 0)进行特殊处理时。
one当某种语言要求对 1 这类数字(如英语和大多数其他语言中的数字 1;在俄语中,任何末尾为 1 但非 11 的数字均属此类)进行特殊处理时。
two当某种语言要求对 2 这类数字(如威尔士语中的 2,或斯洛文尼亚语中的 102)进行特殊处理时。
few当某种语言要求对“小”数字(如捷克语中的 2、3 和 4;或波兰语中末尾为 2、3 或 4,但非 12、13 或 14 的数字)进行特殊处理时。
many当某种语言要求对“大”数字(如马耳他语中末尾为 11 至 99 的数字)进行特殊处理时。
other当某种语言未要求对给定数量(如中文中的所有数字,或英语中的 42)进行特殊处理时。

示例:
保存在 res/values/strings.xml 的 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>

保存在 res/values-pl/strings.xml 的 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` 传递第三个参数。getQuantityString

格式和样式

关于如何正确设置字符串资源的格式和样式,您应了解以下几个要点。

设置字符串格式

如需设置字符串的格式,您可以在字符串资源中放入格式参数(如以下示例资源所示)。

<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>

如果您未应用格式设置,则可以通过 调用 setText(java.lang.CharSequence) 直接设置 TextView 文本。但在某些情况下,您可能想创建带样式的文本资源,并将其用作格式字符串。 您通常无法实现此目标,因为 format(String, Object...)getString(int, Object...) 方法会删除字符串中的所有样式信息。解决方法是编写带转义 实体的 HTML 标记,并在完成格式设置后通过 fromHtml(String) 恢复这些实体。例如:

  1. 将您带样式的文本资源存储为 HTML 转义字符串:
    <resources>
      <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
    </resources>

    如上所示,带格式的字符串中添加了 <b> 元素。请注意,开括号使用 &lt; 表示法进行了 HTML 转义。

  2. 然后照常设置字符串格式,但还需调用 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 软件包中定义的样式应用于文本。

您可以使用以下辅助方法设置创建 Spannable 文本的大量工作:

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);
        }
    }
}

以下 bolditaliccolor 方法包含上述辅助方法,并展示应用 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 模块还包含扩展函数,便于您更轻松地使用 span。您可以查看 GitHub 上的 android.text 软件包文档,了解详情。

如需了解有关使用 span 的更多信息,请访问以下链接:

使用注解设置样式

您可以通过使用 strings.xml 资源文件中的 Annotation 类和 <annotation> 标记,应用复杂样式或自定义样式。借助注解标记,您可以通过在 XML 中定义自定义键值对来标记自定义样式的部分字符串,框架随后会将该 XML 转换成 Annotation span。然后,您便可检索这些注解,并使用键和值来应用样式。

创建注解时,请务必为 strings.xml 文件中的所有字符串翻译添加 <annotation> 标记。


在所有语言中向“text”一词应用自定义字体

示例 - 添加自定义字体

  1. 添加 <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>
  2. 加载字符串资源并找到包含 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 和文本打包

由于 Annotation span 也是 ParcelableSpans,因此需要对键值对进行打包和解包。只要包的接收方了解如何解释注解,您便可使用 Annotation span 向已打包的文本应用自定义样式。

如要在向 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);

SpannableString 的形式从 Bundle 中检索文本,然后解析附加的注解(如上例所示)。

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);

如需了解有关文本样式设置的更多信息,请访问以下链接: