Android string xml string format

Android string.xml resource formatting

EnvyAndroid

Read more posts by this author.

EnvyAndroid

If you are using the strings.xml file for your applications string resources (which you should!) then you might have wondered what to do if you need to combine a string and a value.

Take this text for example:

Hi, my name is Ruben and I am 26 years old

String resource formatting

This can easily be solved by using string formatting to insert the values; Ruben and 26.

In you strings.xml file, create a new string resource like this:

You can then use and format this string resource in you java code like this:

Explanation

As you probably understand, the %1$s is a string placeholder, while the %2$d is an integer placeholder.

The numbers, 1 and 2, are not necessary, but can be used to alter the order of variables. This way, you could use the name parameter several places if you wanted, by creating a string resource like this:

And use it with the same java code.

You can also insert float variables, specify number of decimals and more.

For more information, check out the Android developer documentation on String resources and the java Formatter helper.

Do you have any other tricks that you use regarding strings or formatting?

Источник

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.

Читайте также:  Навигаторы 7 дюймов с видеорегистратором андроид

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.

Читайте также:  Cube acr не записывает разговор андроид 10
  • Then format the string as usual, but also call fromHtml(String) to convert the HTML text into styled text:
  • 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 string.xml — несколько вещей, которые стоит помнить

    Доброго времени суток! Представляю вашему вниманию вольный перевод статьи от GDE (Google developer expert) Dmytro Danylyk. Собственно, вот оригинал. Статья описывает правильные подходы для работы со strings.xml и особенно полезно это будет разработчикам, которые разрабатывают мультиязыковые приложения. Прошу под кат.

    Эта статья о такой тривиальной вещи android как string.xml.

    Не используйте повторно

    Не используйте повторно строки для разных экранов

    Давайте представим, что у вас есть loading dialog на Sign In либо Sign Up экране. Так как оба экрана имеют loading dialog, вы решаете использовать те же строки — R.string.loading.

    Позже, если вы решите использовать различные, вам нужно будет создать 2 разные строки и модифицировать их, непосредственно, в .java классах. Если вы используете разные строки с начала — вам бы пришлось модифицировать лишь strings.xml файл.

    Вы никогда не будете заранее знать поддержку и перевод какого языка вам предстоит добавить. Всё дело в контексте: в одном языке вы можете использовать тоже слово в одном контексте, но в другом — это слово по смыслу не будет подходить.

    Обратите внимание, что в данном случае английская версия strings.xml использует тоже самое слово — “Yes” для обоих случаев R.string.download_file_yes и R.string.terms_of_use_yes strings.
    Но украинский вариант strings.xml использует 2 разных слова — “Гаразд” для R.string.download_file_yes и “Так” для R.string.terms_of_use_yes.

    Разделяйте

    Разделяйте строки, которые относятся к одному экрану с помощью префиксов и комментариев

    1. Добавляйте префикс в виде имени экрана к каждой строке для более простого понимания к какому экрану относится данный ресурс.
    2. Чистый string.xml файл поможет достаточно легко поддерживать и переводить различные языки — экран за экраном.

    Создание различных strings.xml для каждого экрана

    Если вы хотите, вы можете создать string.xml файл для каждого экрана — settings-strings.xml, profile-strings.xml. Но обычно приложение имеет около 10-20 экранов, соответственно, нужно иметь 10-20 string.xml файлов в каждой языковой папке. Я думаю, что это будет сопряжено с беспорядком.

    Форматирование

    Используйте Resources#getString(int id, Object… formatArgs) для форматирования строк

    Никогда не делайте конкатенацию через + оператор, поскольку в других языках порядок слов может варьироваться.

    Множественное число

    Используйте Resources#getQuantityString(int id, int quantity) для количественных строк

    Не решайте проблемы с множественным числом в java коде, поскольку разные языки имеют разные правила для согласования множественного числа

    Подстветка слов

    Используйте html text для подсветки статический слов

    Источник

    Оцените статью