Android R.string(string.xml)


在项目中代码中尽可能少出现中文(注释除外),对此,就需要将字符串设置到string.xml中

通常用法
EXAMPLE 1:
    string.xml中配置:<string name="hello">Hello!</string>
    layout xml中使用方式为:

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

    code 中使用方式为:

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

当然string.xml中也允许设置字符串数组
EXAMPLE 2:
    string.xml中配置:

<string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
</string-array>

    code 中使用方式为:

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

需要注意的是,在配置文件中会使用到特殊字符,eg:英文状态下的单引号“\'”    ,换行符“\n”, 百分号“\%”, “\@”符号
EXAMPLE 3:
    string.xml中配置:正确:

<string name="good_example">"This'll work"</string>                --在双引号中仅仅是作为字符串输出
<string name="good_example_2">This\'ll also work</string>        --不带双引号,则需要考虑转义字符
<string name="good_example_3" formatted="false">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>

当然,string.xml中也支持通配符方式
EXAMPLE 4:
    string.xml中配置:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
%1、%2代表参数的顺序,$s表示输出字符串,$d表示输出十进制整数, $f表示输出十进制浮点数

    code 中使用方式为:

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

最后是带HTML样式的字符串
EXAMPLE 5:
    string.xml中配置:

<string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
                      这里需要注意的是转义字符的使用,eg:< 或 &,可参考EXAMPLE 3

    code 中使用方式为:

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

     这里需要注意参数1:username,如果username中包含了特殊字符 < 或 & 时,需要将其中的特殊字符转义

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

根据官府文档的介绍就到这里,其中还缺少一个关于特殊字符Quantity String的用法,没看明白官方文档的说明也比较少用到,就忽略吧

posted @ 2014-12-15 11:09  rfheh  阅读(2877)  评论(0)    收藏  举报