Android 字符串资源

本文详细介绍了Android应用中字符串资源的三种类型:单字符串、字符串数组和数量字符串(Plurals),并提供了如何在XML文件和Java代码中引用这些资源的方法。此外,文章还阐述了如何为字符串添加样式和格式,以及如何处理不同语言中的数量规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String Resources

A string resource provides text strings for your applicationwith optional text styling and formatting. There are three types of resources that can provideyour 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 different quantities of the same word or phrase.

All strings are capable of applying some styling markup and formatting arguments. Forinformation about styling and formatting strings, see the section about Formatting and Styling.

String

A single string that can be referenced from the application or from other resource files (suchas an XML layout).

Note: A string is a simple resource that is referencedusing the value provided in the name attribute (not the name of the XML file). So, you cancombine 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's name will be used as theresource ID.
compiled resource datatype:
Resource pointer to a String.
resource reference:
In Java: 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:
<resources>
Required. This must be the root node.

No attributes.

<string>
A string, which can include styling tags. Beware that you must escape apostrophes andquotation marks. For more information about how to properly style and format your strings see Formatting and Styling, below.

attributes:

name
String. A name for the string. This name will be used as the resourceID.
example:
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>

This layout XML applies a string to a View:

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

This application code retrieves a string:

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

You can use either getString(int) orgetText(int) to retrieve a string. getText(int) will retain 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 referencedusing the value provided in the name attribute (not the name of the XML file). Assuch, 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's name will be used as theresource ID.
compiled resource datatype:
Resource pointer to an array of Strings.
resource reference:
In Java: R.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:
<resources>
Required. This must be the root node.

No attributes.

<string-array>
Defines an array of strings. Contains one or more <item> elements.

attributes:

name
String. A name for the array. This name will be used as the resourceID to reference the array.
<item>
A string, which can include styling tags. The value can be a referenced to anotherstring resource. Must be a child of a <string-array> element. Beware that youmust escape apostrophes andquotation marks. See Formatting and Styling, below, forinformation about to properly style and format your strings.

No attributes.

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:

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'dwrite "n books". This distinction between singular and plural is very common, but otherlanguages 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 asgetQuantityString() to selectthe appropriate resource for you.

Note that the selection is made based on grammatical necessity. A string for zeroin English will be ignored even if the quantity is 0, because 0 isn't grammatically differentfrom 2, or any other number except 1 ("zero books", "one book", "two books", and so on).Don't be misled either by the fact that, say, two sounds like it could only apply tothe quantity 2: a language may require that 2, 12, 102 (and so on) are all treated like oneanother but differently to other quantities. Rely on your translator to know what distinctionstheir language actually insists upon.

It's often possible to avoid quantity strings by using quantity-neutral formulations such as"Books: 1". This will make your life and your translators' lives easier, if it's a style that'sin keeping with your application.

Note: A plurals collection is a simple resource that isreferenced using the value provided in the name attribute (not the name of the XMLfile). As such, you can combine plurals resources with other simple resources in the oneXML file, under one <resources> element.

file location:
res/values/filename.xml
The filename is arbitrary. The <plurals> element's name will be used as theresource ID.
resource reference:
In Java: 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:
<resources>
Required. This must be the root node.

No attributes.

<plurals>
A collection of strings, of which, one string is provided depending on the amount ofsomething. Contains one or more <item> elements.

attributes:

name
String. A name for the pair of strings. This name will be used as theresource ID.
<item>
A plural or singular string. The value can be a referenced to anotherstring resource. Must be a child of a <plurals> element. Beware that you mustescape apostrophes and quotation marks. See Formatting andStyling, below, for information about to properly style and format your strings.

attributes:

quantity
Keyword. A value indicating when this string should be used. Validvalues, with non-exhaustive examples in parentheses:
ValueDescription
zeroWhen the language requires special treatment of the number 0 (as in Arabic).
oneWhen the language requires special treatment of numbers like one (as with the number 1 in English and most other languages; in Russian, any number ending in 1 but not ending in 11 is in this class).
twoWhen the language requires special treatment of numbers like two (as in Welsh).
fewWhen the language requires special treatment of "small" numbers (as with 2, 3, and 4 in Czech; or numbers ending 2, 3, or 4 but not 12, 13, or 14 in Polish).
manyWhen the language requires special treatment of "large" numbers (as with numbers ending 11-99 in Maltese).
otherWhen the language does not require special treatment of the given quantity.
example:
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="numberOfSongsAvailable">
        <item quantity="one">One 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 jedną piosenkę.</item>
        <item quantity="few">Znaleziono %d piosenki.</item>
        <item quantity="other">Znaleziono %d piosenek.</item>
    </plurals>
</resources>

Java code:

int count = getNumberOfsongsAvailable();
Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);

When using the getQuantityString() method, you need to pass the count twice if your string includesstring formatting with a number. For example, for the string%d songs found, the first count parameter selects the appropriate plural string andthe second count parameter is inserted into the %d placeholder. If your pluralstrings do not include string formatting, you don't need to pass the third parameter to getQuantityString.

Formatting and Styling

Here are a few important things you should know about how to properlyformat and style your string resources.

Escaping apostrophes and quotes

If you have an apostrophe or a quote in your string, you must either escape it or enclose thewhole string in the other type of enclosing quotes. For example, here are some stings thatdo and don't work:

<string name="good_example">"This'll work"</string>
<string name="good_example_2">This\'ll also work</string>
<string name="bad_example">This doesn't work</string>
<string name="bad_example_2">XML encodings don&apos;t work</string>

Formatting strings

If you need to format your strings using String.format(String, Object...),then you can do so by puttingyour format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$dis a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(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>

Supported HTML elements include:

  • <b> for bold text.
  • <i> for italic text.
  • <u> for underline text.

Sometimes you may want to create a styled text resource that is also used as a formatstring. Normally, this won't work because the String.format(String, Object...)method will strip all the styleinformation from the string. The work-around to this is to write the HTML tags with escapedentities, which are then recovered with fromHtml(String),after the formatting takes place. For example:

  1. Store your styled text resource as an HTML-escaped string:
    <resources>
      <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
    </resources>

    In this formatted string, a <b> element is added. Notice that the opening bracket isHTML-escaped, using the &lt; notation.

  2. Then format the string as usual, but also call fromHtml(String) toconvert the HTML text into styled text:
    Resources res = getResources();
    String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
    CharSequence styledText = Html.fromHtml(text);

Because the fromHtml(String) method will format all HTML entities, be sure toescape any possible HTML characters in the strings you use with the formatted text, usinghtmlEncode(String). For instance, if you'll be passing a string argument toString.format() that may contain characters such as"<" or "&", then they must be escaped before formatting, so that when the formatted stringis passed through fromHtml(String), the characters come out the way they wereoriginally written. For example:

String escapedUsername = TextUtil.htmlEncode(username);

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值