2011年8月13日 星期六

[Resources] String Resources

* string resources 可置於 /res/strings.xml 中

R.string.string_name
<resources>
    <string name="string_name">string resources</string>
</resources>

或設定 string arrays

R.array.string_array_name
<resources>
    <string-arrays name="string_array_name">
        <item>aaa</item>
    </string-arrays>
</resources>

* 取得resource的方式是以string_name做為區別,因此檔名命名並不被限制,也可將其他resources放在同個檔案中(ex: color, dimen...)。

* 字串中 ' 和 " 須被escape (\' and \")

* 若要顯示 % 則是要用 % 做escape

Formatting strings

in .xml

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

%1$s is a string , %2$d is a decimal number

in .java

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

or

in .xml


<string name="">免費使用期限為{0}年{1}月{2}日</string>

in .java
String msg = getResources().getString(R.string.app_termination_msg);
msg = MessageFormat.format(msg, appName, endDate);
mMsg.setText(msg);


Styling with HTML markup
  • Can using some HTML tag to style string
  • ex: <b>, <i>, <u>
  • 加了 HTML tag 的 string 使用時則要透過 Html.fromHtml(text); 設定
  • format string 時,在欲指定的string中也能包含HTML,但在format前必須先經由TextUtil.htmlEncode(text); encode。


* Reference
- String Resources
- JAVA String.format 方法使用介绍

沒有留言:

張貼留言