您的位置:首页 > 移动开发 > Android开发

String Resources

2016-04-05 12:41 686 查看
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:

StringXML resource that provides a single string.String ArrayXML 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 
<resources>
 element.
FILE LOCATION:
res/values/filename.xml


The filename is arbitrary. The 
<string>
 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:
<?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 and quotation 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 resource ID.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 = [code]getString
(R.string.hello);[/code]
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 
<resources>
 element.
FILE LOCATION:
res/values/filename.xml


The filename is arbitrary. The 
<string-array>
 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:
<?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 resource ID to reference the array.
<item>
A string, which can include styling tags. The value can be a reference to another string resource. Must be a child of a 
<string-array>
 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.
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 = [code]getResources()
;
String[] planets = res.
getStringArray
(R.array.planets_array);[/code]


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 
<resources>
 element.
FILE LOCATION:
res/values/filename.xml


The filename is arbitrary. The 
<plurals>
 element's 
name
 will be used as the resource 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 of something. Contains one or more 
<item>
 elements.
attributes:
name
String. A name for the pair of strings. This name will be used as the resource ID.
<item>
A plural or singular string. The value can be a reference to another string resource. Must be a child of a 
<plurals>
 element. Beware that you must escape apostrophes and quotation marks. SeeFormatting
and Styling, below, for information about to properly style and format your strings.
attributes:
quantity
Keyword. A value indicating when this string should be used. Valid values, with non-exhaustive examples in parentheses:
ValueDescription
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 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 file saved at 
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>

Java code:
int count = getNumberOfsongsAvailable();
Resources res = [code]getResources()
;
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);[/code]
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 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:
<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>
    <!-- Causes a compile error -->


If you have a double-quote in your string, you must escape it (
\"
). Surrounding the string with single-quotes does not work.
<string name="good_example">This is a \"good string\".</string>
<string name="bad_example">This is a "bad string".</string>
    <!-- Quotes are stripped; displays as: This is a bad string. -->
<string name="bad_example_2">'This is another "bad string".'</string>
    <!-- Causes a compile error -->


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:
<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$d
 is a decimal number. You can format the string with arguments from your application like this:
Resources res = [code]getResources()
;
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);[/code]


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 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:
<resources>
  <string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
</resources>

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

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

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 "<" or "&", then they must be escaped before formatting, so that when the formatted string is passed through 
fromHtml(String)
,
the characters come out the way they were originally written. For example:
String escapedUsername = TextUtil.[code]htmlEncode
(username);

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


Styling with Spannables

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:
/**
 * 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 apply(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);
        }
    }
}


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.
/**
 * 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));
}


Here's an example of how to chain these methods to create a character sequence with different types of styling applied to individual words:
// Create an italic "hello, " a red "world",
// and bold the entire sequence.
CharSequence text = bold(italic(res.getString(R.string.hello)),
    color(Color.RED, res.getString(R.string.world)));
字符串资源提供的文本字符串与可选的文本样式和格式应用程序。有三种类型,可以提供您的应用程序使用字符串资源:
XML资源,提供一个字符串。字符串数组XML资源,提供一个字符串数组。数量字符串(复数)携带对复数不同的字符串XML资源。所有字符串都可以应用一些样式标记和格式化参数的。有关样式和格式字符串的信息,请参阅有关的章节格式和样式

可以从应用程序或其他资源文件(如XML布局)引用一个字符串。注意:一个字符串是使用在提供的值引用的一个简单的资源
名称
属性(未XML文件的名称)。所以,你可以字符串资源与其他资源的简单一个XML文件中结合起来,在一个
<资源>
元素。文件位置:
RES /价值/ 文件名 ​​的.xml

的文件名 ​​是任意的。该
<字符串>
元素的
名称
将用作资源ID。编译的资源数据类型:资源指针指向一个
字符串
。资源引用:在Java:
。R.string string_name

在XML:
@字符串/ string_name
句法:
<?XML版本= “1.0” 编码= “UTF-8” ?>
< 资源 >
    < 字符串
        名称= “ string_name ”
        > text_string的 </字符串>
</资源>
内容:
<资源>
必选项。这必须是根节点。无属性。
<字符串>
一个字符串,它可以包括造型标签。当心,你必须逃脱撇号和引号。有关如何正确风格和格式化你的字符串更多信息,请格式和样式,如下。属性:
名称
字符串。一种字符串名称。这个名称将被用作资源ID。例:在保存XML文件
RES /价值/ strings.xml中
<?XML版本= “1.0” 编码= “UTF-8” ?>
<资源>
    <字符串 名称= “你好” > 您好!</字符串>
</资源>
这种布局XML应用一个字符串视图:<TextView
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:text = "@string/hello" />此应用程序代码检索字符串:字符串 字符串 =
的getString
(ř 。字符串。你好);您可以使用
的getString(INT)
或 
gettext的(INT)
来检索字符串。
gettext的(INT)
将保留应用到任何字符串丰富的文本样式。

字符串数组

字符串数组,可以从应用程序引用。注意:一个字符串数组,是使用在提供的值引用的一个简单的资源
名称
属性(未XML文件的名称)。因此,您可以在一个XML文件中与其他简单的资源整合字符串数组资源,在一个
<资源>
元素。文件位置:
RES /价值/ 文件名 ​​的.xml

的文件名 ​​是任意的。所述
<串阵列>
元素的
名字
将被用作资源ID。编译的资源数据类型:资源指针数组
的String
秒。资源引用:在Java:
。R.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>
内容:
<资源>
必选项。这必须是根节点。无属性。
<字符串数组>
定义字符串数组。包含一个或多个
的<item>
元素。属性:
名称
字符串。一种数组名。这个名称将被作为资源ID,以引用的阵列。
<项目>
一个字符串,它可以包括造型标签。该值可以是到另一个字符串资源的参考。必须是一个孩子
<字符串数组>
元素。当心,你必须逃脱撇号和引号。见格式和样式,下面,关于正确的风格和格式化字符串的信息。无属性。例:在保存XML文件
RES /价值/ 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>
此应用程序代码检索一个字符串数组:资源RES =
getResources ()
;
字符串[] 行星= 资源。
getStringArray
(ř 。数组。planets_array );

数量字符串(复数)

不同的语言有与数量语法的协议不同的规则。在英语中,例如,所述的数量1是一种特殊情况。我们写“1书”,但对于任何其他数据,我们会写“ ñ书”。单数和复数之间的区别是很常见的,但其他语言做出更细的区分。由Android支持的全套是
, 
1
2
很多
,和
其他
。决定哪一种情况下,使用一个给定的语言和数量的规则可能非常复杂,因此Android为您提供了方法,如
getQuantityString()
来选择合适的资源给你。尽管历史上所谓的“量字符串”(现在仍然叫,在API),数量字符串应该只用于复数。这是使用量的字符串来实现类似Gmail的“收件箱”还是一个错误的“收件箱(12)”,当有未读消息,例如。这似乎方便使用量字符串,而不是一个
,如果
声明,但要注意的是,有些语言(如中国)根本不使这些语法区别是很重要的,所以你永远得到
其他
字符串。该字符串使用作出选择完全基于语法的必要性。在英语中,对于字符串
将即使数量为0被忽略,因为0是不是从语法2不同,或除1(“零的书”,“一书”,“两地书”的任何其他号码,等等)。相反,韩国只在
其他
字符串将被使用。不要被误导或者通过事实,也就是说,
2
听起来像它可能只适用于量2:语言可能需要2,12,102(等)都像对待彼此,但不同于其他数量。依靠您的翻译知道什么区别他们的语言实际上在坚持。它通常尽量避免使用量中性配方量的字符串,如“书:1”。这会让你的生活和译者的生活更轻松,如果它是一个风格,是与您的应用程序保持一致。注意:一复数集合是使用在提供的值引用的一个简单的资源
名称
属性(未XML文件的名称)。因此,您可以在一个XML文件中与其他简单的资源整合复数资源,在一个
<资源>
元素。文件位置:
RES /价值/ 文件名 ​​的.xml

的文件名 ​​是任意的。在
<复数>
元素的
名称
将用作资源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>
内容:
<资源>
必选项。这必须是根节点。无属性。
<复数>
串的集合,其中,根据某些事物的量被提供的一个字符串。包含一个或多个
的<item>
元素。属性:
名称
字符串。一种用于对字符串的名称。这个名称将被用作资源ID。
<项目>
一个复数或单串。该值可以是到另一个字符串资源的参考。必须是一个的子
<复数>
元素。当心,你必须逃脱撇号和引号。见格式和样式,下面,关于正确的风格和格式化字符串的信息。属性:
数量
关键字。说明何时应该使用这个字符串的值。有效值,括号非穷尽的例子:
描述
当语言需要的号码0的特殊处理(如阿拉伯语)。
当语言需要如下的一个数特别处理(如用英语和大多数其他语言的数量1;俄罗斯,任何数量在1结束,但11不是结束是在这个类)。
当语言需要像两个数字的特别处理(与2威尔士,或102斯洛文尼亚)。
少数
当语言需要“小”的数字特殊处理(如用2,3,和在捷克4;或结束2,3,或4而不是12,13,或14中的波兰的数字)。
许多
当语言需要“大”的数字特别处理(如用数字结尾的马耳他11-99)。
其他
当语言不需要一定量的特殊处理(如用在中国的所有数值,或英文42)。
例:在保存XML文件
RES /价值/ strings.xml中
:<?XML版本= “1.0” 编码= “UTF-8” ?>
<资源>
    <复数 名= “numberOfSongsAvailable” >
        <! -
             作为一个开发者,你应该总是提供“一”和“其他”
             的字符串。您的翻译人员知道这实际上是字符串
             需要他们的语言。始终在“一”,因为%d个
             翻译就需要使用%d表示语言,其中“一”
             并不意味着1(如上所述)。
          - >
        <项目 数量= “一” > 。%d个歌找到< /项目>
        <项目 数量= “其他” > %d首歌曲中。</项目>
    </复数>
</资源>在保存XML文件
RES /值-PL / strings.xml中
:<?xml的

   
        %d个piosenkę。</项目>
        <项目 数量= “少数” > Znaleziono%d个piosenki。</项目>
        <项目 数量= “其他” > Znaleziono%d个piosenek。</项目>
    </复数>
</资源>Java代码:int count = getNumberOfsongsAvailable ();
Resources res =
getResources ()
;
String songsFound = res . getQuantityString ( R . plurals . numberOfSongsAvailable , count , count );当使用
getQuantityString()
方法,你需要通过
计数
两次,如果你的字符串包含 字符串格式化与多家。例如,对于串 
发现%d首歌曲
,所述第一
计数
参数选择适当的复数串和所述第二
计数
参数被插入
%d个
占位符。如果您的多个琴弦不包括字符串格式化,你并不需要第三个参数传递给
getQuantityString

格式和样式

下面是你应该知道一些重要的事情如何正确的格式和样式的字符串资源。

转义单引号和报价

如果你有一个单引号(
'
),(在你的字符串,则必须用反斜杠转义
\' 
)或双引号括起来的字符串(
“” 
)。例如,这里有一些字符串和不工作:<字符串 名称= “good_example” > 这\'会工作</字符串>
<字符串 名称= “good_example_2” > “这也将工作的” </字符串>
<字符串 名称= “bad_example” > 这不起作用< /字符串>
    <! -导致编译错误- >如果你在你的字符串中的双引号,你必须转 ​​义(
\“ 
),围绕着单引号的字符串中 不能正常工作。<字符串 名称= “good_example” > 这是一个\“好字符串\”。</字符串>
<字符串 名称= “bad_example” > 这是一个“坏串”。</字符串>
    < -报价剥夺!; 显示为:这是一个错误的字符串。- >
<字符串 名称= “bad_example_2” > “这又是一个”坏串“。” </字符串>
    <! -导致编译错误- >

格式化字符串

如果您需要使用格式化你的字符串
的String.format(字符串,对象...) 
,那么你可以把你的格式参数的字符串资源这样做。例如,用下面的资源:<字符串 名称= “welcome_messages” > 您好,%1 $ S!你有%2 $ d个新邮件。</字符串>在这个例子中,格式字符串有两个参数:
%1 $ S
是一个字符串,
%2 $ d个
 是一个十进制数。您可以格式化从您的应用程序像这样的参数字符串:Resources res =
getResources ()
;
String text = String . format ( res . getString ( R . string . welcome_messages ), username , mailCount );

与HTML标记的样式

您可以添加样式与HTML标记的字符串。例如:<?XML版本= “1.0” 编码= “UTF-8” ?>
<资源>
    <字符串 名称= “欢迎” > 欢迎<B> 的Android </ B> !</字符串>
</资源>支持的HTML元素包括:
<B>
粗体文字。
<I>
为斜体文字。
<U>
下划线的文本。
有时你可能想创建一个也用作格式字符串样式文本资源。通常情况下,这将无法工作,因为
的String.format(字符串,对象...)
 方法将去除从字符串的所有样式信息。该工作周围,这是与实体逃脱,然后与回收写HTML标签
fromHtml(字符串)
,格式化发生之后。例如:存储您的样式文本资源作为一个HTML转义字符串:
<资源>
  <字符串 名称= “welcome_messages” > 您好,%1 $ S!你有&LT; b>%2 $ d个新消息&LT; / B> </字符串>
</资源>
在这个格式化字符串,一个
<B>
元素添加。请注意,左括号是HTML转义,使用
&LT;
符号。
然后格式化字符串像往常一样,还叫
fromHtml(字符串)
的HTML文本转换为样式文本:
Resources res =  [code]getResources ()
;
String text = String . format ( res . getString ( R . string . welcome_messages ), username , mailCount );
CharSequence styledText = Html . fromHtml ( text );[/code]
因为
fromHtml(字符串)
方法将格式化所有HTML实体,一定要逃避你格式化文本使用的字符串的任何可能的HTML字符,使用 
的HTMLEncode(字符串)
。举例来说,如果你将传递一个字符串参数 
的String.format()
可能包含字符,如“<”或“&”,那么他们必须在格式化之前,这样当格式化字符串穿过逃过一劫,
fromHtml (字符串)
,人物出来最初编写的方式。例如: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 );

与Spannables造型

一个
Spannable
是一个文本对象,您可以用字体属性,如颜色和字体粗细的风格。您可以使用
SpannableStringBuilder
建立你的文本,然后应用在定义的样式
android.text.style
 包到文本。您可以使用下面的辅助方法,建立多创造spannable文本的工作:/ **
 *返回并置的CharSequence指定数组一个的CharSequence
 *的对象,然后应用的零个或多个标签的整个范围内的清单。
 *
 * @参数内容的字符序列的数组应用样式
 * @参数标签在风格跨度对象应用到内容
 *如

   

   

   

   

 在tag数组的迭代,并将它们应用到指定的开始
 * Spannable对象,以便附加到文本未来文本将有造型
 *适用于它。不要调用此方法

   

   

 通过更新跨度为“关闭”在Spannable指定标记
 *端点独占使追加到末尾未来的文本不会采取
 *在同一个造型。不要调用此方法

   
   
       

       

       
   
下面
加粗
斜体
颜色
 的方法告诉你如何调用helper方法应用在定义的样式
android.text.style
包。您可以创建类似的方法做其他类型的文本造型。/ **
 *返回适用于黑体字串联一个的CharSequence
 指定CharSequence的*

   

 返回适用斜体字串联一个的CharSequence
 指定CharSequence的*

   

 返回应用于前景色到一个的CharSequence
 指定CharSequence的*级联

   
这里有一个如何来链接这些方法来创建应用到各个单词的不同类型的造型的字符序列的例子://创建一个斜体“你好”,一个红色的“世界”,
//和大胆的整个sequence.
CharSequence text = bold ( italic ( res . getString ( R . string . hello )),
    color ( Color . RED , res . getString ( R . string . world )));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息