Android Resource Types之String简介

来源:互联网 发布:js 数组和对象 编辑:程序博客网 时间:2024/06/06 05:10

官方文档:String Resources

String Resources

string资源为应用程序提供字符串文本,并可附带文本样式和格式。有以下三种类型的string资源可供应用程序使用:

String,单个字符串。
String Array,字符串数组。
Quantity Strings (Plurals),数量字符串(复数)。

1.String

文件位置:

res/values/filename.xml

文件引用:

In Java: R.string.string_nameIn XML:@string/string_name

句法:

<?xml version="1.0" encoding="utf-8"?><resources>    <string        name="string_name"        >text_string</string></resources>

例子:
XML文件保存在res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="hello">Hello!</string></resources>

在布局文件中引用:

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

Java代码检索字符串:

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

可使用getString(int)或getText(int)方法检索字符串,两者区别为getText(int)返回的字符串附带文本样式。

2.String Array

文件位置:

res/values/filename.xml

文件引用:

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

例子:
XML文件保存在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>

Java代码检索字符串数组:

Resources res = getResources();String[] planets = res.getStringArray(R.array.planets_array);

3.Quantity Strings (Plurals)

不同的语言对数量进行描述的语法规则是不同的。比如在英语里,数量1是个特殊情况,我们写成”1 book”,但其他任何数量都要写成”n books”。这种单复数之间的区别是很普遍的,不过其他语言会有更好的区分方式。Android支持的全集包括zero、one、 two、few、many和other。
决定选择和使用某种语言和复数的规则是非常复杂的,所以Android提供了诸如getQuantityString()的方法来选择合适的资源。

文件位置:

res/values/filename.xml

文件引用:

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

例子:
XML文件保存在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>

Java代码:

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

在使用getQuantityString()方法时,如果字符串包含数字格式化串,则需要传递2个count参数。例如:对于字符串”%d songs found”,第一个count参数选择合适的复数字符串,第二个count参数插入占位符%d中。如果复数字符串资源不包含格式化信息,就不需要给getQuantityString()传递第三个参数。

4.Formatting and Styling

4.1 Escaping apostrophes and quotes:单引号和双引号的转义
如果字符串里包含单引号或双引号,必须进行转义(\’或\”) ,或者把整个串封闭在与当前引号不同的成对的引号内。

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

4.2 Formatting strings:格式化字符串
如果需要使用String.format(String, Object…)格式化字符串,可以把格式化参数放在字符串(string)资源里。

例子:

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

此例中存在两个参数:%1sd 是个数字。则在应用程序中可以用如下方式用参数来格式化字符串:

Resources res = getResources();String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

4.3 Styling with HTML markup:用HTML标记来样式化
可以用HTML 标记来为字符串加入样式。例如:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="welcome">Welcome to <b>Android</b>!</string></resources>

支持以下HTML元素:

<b>文本加粗bold。<i>文本变斜体italic。<u>文本加下划线underline。

1).将样式化的文本资源存储为转义后的HTML字符串:

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

2).然后,按照通常方式格式化字符串,并调用fromHtml(String) 把HTML文本转换成带样式的文本。

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

因为fromHtml(String)方法会格式化所有的HTML内容,所以要确保用htmlEncode(String)对带格式化文本的字符串内所有可能的HTML字符进行转义。比如,如果要把可能包含诸如”<”或”&”等字符的串作为参数传给String.format(),那么必须在格式化之前对这些字符进行转义。格式化后,再把字符串传入fromHtml(String),这些特殊字符就能还原成本来意义了。例如:

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

4.4 Styling with Spannables:用Spannables来样式化
Spannables是一个文本对象,可用来样式化文本,如颜色和字体粗细等风格。可使用SpannableStringBuilder建立自己的文本,并将在android.text.style包定义的样式应用到文本上。

可用下面的辅助方法来创建spannable文本:

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

下面的bold,italic,和color方法用来将android.text.style包定义的样式应用到文本上。可创建类似方法应用其他样式。

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

使用例子:

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