- String Resources
- String
- String Array
- Quantity Strings (Plurals)
- Formatting and Styling
- Escaping apostrophes and quotes
- Formatting strings
- Styling with HTML markup
- Styling with Spannables
- Android SDK Quick Tip: Formatting Resource Strings
- Step 0: Getting Started
- Step 1: Creating the String Resources
- Step 2: Why Use Format Strings?
- Step 3: Creating Format Strings
- Step 4: Supplying Format Strings with Numeric Parameters
- Step 5: Supplying Format Strings with Multiple Parameters
- Bonus: Format String Parameter Order is Flexible and Locale-Friendly
- Conclusion
String Resources
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 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 the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one element.
file location: res/values/filename.xml
The filename is arbitrary. The element’s name will be 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: elements: Required. This must be the root node.
A string, which can include styling tags. Beware that you must escape apostrophes and quotation marks. For more information about how to properly style and format your strings see Formatting and Styling, below.
name String. A name for the string. This name will be used as the resource ID. example: XML file saved at res/values/strings.xml :
This layout XML applies a string to a View:
This application code retrieves a string:
You can use either getString(int) or getText(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 referenced using the value provided in the name 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 one element.
file location: res/values/filename.xml
The filename is arbitrary. The element’s name will be 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 syntax: elements: Required. This must be the root node.
Defines an array of strings. Contains one or more elements.
name String. A name for the array. This name will be used as the resource ID to reference the array. A string, which can include styling tags. The value can be a reference to another string resource. Must be a child of a element. Beware that you must escape apostrophes and quotation marks. See Formatting and Styling, below, for information about to properly style and format your strings.
example: XML file saved at res/values/strings.xml :
This application code retrieves a string 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 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 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 will be 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 will ever be 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.
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’s in keeping with your application.
Note: A plurals collection is a simple resource that is referenced using the value provided in the name 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 one element.
file location: res/values/filename.xml
The filename is arbitrary. The
element’s name will be used as the resource ID. resource reference: In Java: R.plurals.plural_name syntax: elements: Required. This must be the root node.
A collection of strings, of which, one string is provided depending on the amount of something. Contains one or more elements.
name String. A name for the pair of strings. This name will be used as the resource ID. A plural or singular string. The value can be a reference to another string resource. Must be a child of a
element. Beware that you must escape apostrophes and quotation marks. See Formatting and Styling, below, for information about to properly style and format your strings.
quantity Keyword. A value indicating when this string should be used. Valid values, with non-exhaustive examples in parentheses:
Value | Description |
---|---|
zero | When the language requires special treatment of the number 0 (as in Arabic). |
one | When 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). |
two | When the language requires special treatment of numbers like two (as with 2 in Welsh, or 102 in Slovenian). |
few | When 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). |
many | When the language requires special treatment of «large» numbers (as with numbers ending 11-99 in Maltese). |
other | When the language does not require special treatment of the given quantity (as with all numbers in Chinese, or 42 in English). |
example: XML file saved at res/values/strings.xml :
XML file saved at res/values-pl/strings.xml :
When using the getQuantityString() method, you need to pass the count twice if your string includes string formatting with a number. For example, for the string %d songs found , the first count parameter selects the appropriate plural string and the second count 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 to getQuantityString .
Formatting and Styling
Here are a few important things you should know about how to properly format and style your string resources.
Escaping apostrophes and quotes
If you have an apostrophe ( ‘ ) in your string, you must either escape it with a backslash ( \’ ) or enclose the string in double-quotes ( «» ). For example, here are some strings that do and don’t work:
If you have a double-quote in your string, you must escape it ( \» ). Surrounding the string with single-quotes does not work.
Formatting strings
If you need to format your strings using String.format(String, Object. ) , then you can do so by putting your format arguments in the string resource. For example, with the following resource:
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Styling with HTML markup
You can add styling to your strings with HTML markup. For example:
Supported HTML elements include:
Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won’t work because the String.format(String, Object. ) method will 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 fromHtml(String) , after the formatting takes place. For example:
- Store your styled text resource as an HTML-escaped string:
In this formatted string, a element is added. Notice that the opening bracket is HTML-escaped, using the notation.
Because the fromHtml(String) method will format 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’ll be passing a string argument to String.format() that may contain characters such as » fromHtml(String) , the characters come out the way they were originally written. For example:
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 the android.text.style package to the text.
You can use the following helper methods to set up much of the work of creating spannable text:
The following bold , italic , and color methods show you how to call the helper methods to apply styles defined in the android.text.style package. You can create similar methods to do other types of text styling.
Here’s an example of how to chain these methods to create a character sequence with different types of styling applied to individual words:
Источник
Android SDK Quick Tip: Formatting Resource Strings
This quick tip shows you how to create and use string resources as format strings. You will achieve this by creating and configuring the appropriate string resources in XML and using them programmatically to supply the various typed parameters.
Step 0: Getting Started
Begin by creating an Android project. If you’d like to just follow along, you can find a sample project with code for formatting strings.
Step 1: Creating the String Resources
String resources are often stored within the /res/values/strings.xml file of the resource hierarchy. Any strings you add to the strings.xml file will be accessible within your application. The following is a sample strings.xml file:
This string resource file defines two strings. One for the application name and another called hello. Remember that if your string resource has complex character codes, you may need to quote the entire string. You can add format string resources much as you do regular string resources.
Step 2: Why Use Format Strings?
Format strings are a convenient way to build up one string that has variable content. This is best illustrated by example. In homage to the popular video game Oregon Trail, let’s look at an infamous message players inevitably saw while dragging their family across the Midwest:
«You shot > pounds of meat!»
The number of pounds of game meat changes based upon how the player shoots. There are a number of ways (both good and bad) that developers might approach this problem. A developer might:
- Avoid the problem entirely and create a generic string, shying away from the specifics: «You shot something!»
- Create two string resources (e.g. «You shot » and » pounds of meat!») and sandwich them together around a number programmatically.
- Brew their own solution, doing some black magic with string search and replace methods (e.g. «You shot ##PUT_NUM## pounds of meat!» and the String replace() method).
- Ask themselves if format strings work in Android resource files and read this tutorial.
We didn’t make these approaches up. We’ve seen them all. Only two of these approaches are reasonable: the first and the last.
Sometimes, coming up with a generic string is the right answer—it’s simple and straightforward. Generally, this is the best approach when the information being relayed can be made generic without the application losing something. Other times, you need to communicate important and specific information to the user. In Oregon Trail, if you shot 2 pounds of meat, then you’d keep hunting (or starve), whereas, if you shot 1234 pounds of game, your wagon was maxed out anyway, so you’d likely choose to mosey along down the trail (with a full belly).
You might ask why the sandwich approach isn’t so great. First, using two strings clutters your resource files and makes them difficult to maintain. Secondly, when you go to internationalize your application, you may find that those two strings are no longer appropriate—it can get very complex if your string has more than one parameter, too. Brewing your own solution means introducing more code to maintain and assuming that you can do string manipulation better than the stock Java libraries can.
Better to use the standard methods for formatting strings and create a single string resource with parameters.
Step 3: Creating Format Strings
Format strings can have one parameter or many. Each parameter is numbered and typed. The parameter number is specified using % followed by the number of the parameter, which corresponds to the order in which the parameter values will be supplied programmatically. For example, the first parameter would be %1, the second %2, etc. The second item each parameter has is a type (think C-style printf()), specified by a $ and a letter specifying that type.
For example, a string would be $s; a number might be $d. Therefore, our string resource could be crafted as:
Step 4: Supplying Format Strings with Numeric Parameters
Now that you’ve created a proper format string, you can load it, format it, and display it to users. The following code loads the string resource, supplies the single numeric parameter and generates the completed string:
Step 5: Supplying Format Strings with Multiple Parameters
Let’s try another example. This time we’ll create two more format string resources, each with two parameters. In Oregon Trail, the player’s family often got sick and sometimes died. The two messages players often saw went something like this:
» > has >!»
and
» > has killed >!»
Creating the two format string resources is fairly straightforward:
The following code loads the string resources, supplies the parameters, and generates the completed strings:
Bonus: Format String Parameter Order is Flexible and Locale-Friendly
You may have noticed in the last step that the parameters were swapped in the second string (strDisease2Msg). This is a little annoying, no? Luckily, there’s absolutely no reason format string contents must dictate the order of the parameters. Instead, simply number the parameters in the format string resource in the order that you want to supply them. For example, if you always want to supply the character name, followed by the disease name, then define your format string like this:
Therefore, your code would then look like this:
That makes it much easier on the developer. Also, in terms of string translation, many of the string parameters get jumbled up in different languages anyway.
Conclusion
In this quick tip you learned how to use format strings as Android string resources. Format strings allow for flexible and maintainable application assets.
Источник