格式和樣式設(shè)置
關(guān)于如何正確設(shè)置字符串資源的格式和樣式,您應(yīng)該了解下面這幾個(gè)要點(diǎn)。
轉(zhuǎn)義撇號(hào)和引號(hào)
如果字符串中包含撇號(hào) ('),您必須用反斜杠 (') 將其轉(zhuǎn)義,或?yàn)樽址由想p引號(hào) ("")。 例如,以下是一些有效和無(wú)效的字符串:
<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>
如果字符串中包含雙引號(hào),您必須將其轉(zhuǎn)義(使用 ")。 為字符串加上單引號(hào)不起作用。
<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 -->
設(shè)置字符串格式
如果您需要使用 String.format(String, Object...)設(shè)置字符串格式,可以通過(guò)在字符串資源中加入格式參數(shù)來(lái)實(shí)現(xiàn)。 例如,對(duì)于以下資源:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
在本例中,格式字符串有兩個(gè)參數(shù):%1$s 是一個(gè)字符串,而 %2$d 是一個(gè)十進(jìn)制數(shù)字。 您可以像下面這樣使用應(yīng)用中的參數(shù)設(shè)置字符串格式:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
使用 HTML 標(biāo)記設(shè)置樣式
您可以使用 HTML 標(biāo)記為字符串添加樣式設(shè)置。例如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="welcome">Welcome to <b>Android</b>!</string>
</resources>
支持的 HTML 元素包括:
-
<b>表示粗體文本。 -
<i>表示斜體文本。 -
<u>表示<u>下劃線(xiàn)</u>文本。
有時(shí),您可能想讓自己創(chuàng)建的帶樣式文本資源同時(shí)也用作格式字符串。 正常情況下,這是行不通的,因?yàn)?String.format(String, Object...)方法會(huì)去除字符串中的所有樣式信息。 這個(gè)問(wèn)題的解決方法是編寫(xiě)帶轉(zhuǎn)義實(shí)體的 HTML 標(biāo)記,在完成格式設(shè)置后,這些實(shí)體可通過(guò) fromHtml(String) 恢復(fù)。 例如:
- 將您帶樣式的文本資源存儲(chǔ)為 HTML 轉(zhuǎn)義字符串:
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
</resources>
在這個(gè)帶格式的字符串中,添加了 <b> 元素。請(qǐng)注意,開(kāi)括號(hào)使用 < 表示法進(jìn)行了 HTML 轉(zhuǎn)義。
- 然后照常設(shè)置字符串格式,但還要調(diào)用
fromHtml(String)以將 HTML 文本轉(zhuǎn)換成帶樣式文本:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
由于 fromHtml(String) 方法將設(shè)置所有 HTML 實(shí)體的格式,因此務(wù)必要使用 htmlEncode(String) 對(duì)您用于帶格式文本的字符串中任何可能的 HTML 字符進(jìn)行轉(zhuǎn)義。 例如,如果您向 String.format() 傳遞的字符串參數(shù)可能包含“<”或“&”之類(lèi)的字符,則必須在設(shè)置格式前進(jìn)行轉(zhuǎn)義,這樣在通過(guò) fromHtml(String) 傳遞帶格式字符串時(shí),字符就能以原始形式顯示出來(lái)。 例如:
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);