標籤:android 字串 plurals string xml
如果你開發的應用覆蓋多個國家,在處理數量的問題的時候,一定會碰到根據不同的數量使用不同的字串。
不同的語言在處理數量對待方式不一樣,這種情況非常常見,舉一個簡單的例子說明下中文和英文在修飾數量上的差異:
在中文裡,1本書,2本書,...... n本書,
在英文裡,1 book, 2 books, ...... n books。然而,即使在0的情況下,也要用books, 即0 books.
中文在對待單複數情況下並沒有作區分,而英文就做了區別。除了英文之外,很多語言都做了有類似的區別。另外在有些情況下,我們還要根據不同的數量使用不同的詞彙,像零、一、二、很少、很多,然後就是其它修飾方式。即使在這一點上, 不同的國家使用的也是不盡相同。
所以涉及到多語言處理數量問題的時候,是個比較棘手的。你不可能在代碼中要根據不同國家的語言使用if語句來進行各種判斷,適配相應的字串,可想而知這些工作都是極其枯燥的。Android系統提供了getQuantityString()方法來處理這個問題,它可以根據不同國家的語言來選擇你預先定義的字串資源。你可以根據不同的國家語言在相應values-xx/strings.xml檔案中定義字串,當然你要按andorid的規則來
下面是資源定義的一個樣本:
<span style="font-size:18px;"><?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></span>
從上面的定義中可以相應的文法使用規則。
<resources>
這是定義資源的所在根。
<plurals>
它是字串的集合,包含你用來修飾不同數量的字串。它可以包含一個或多個<item>元素。
name就是資源的名稱,name在代碼中以reousrce id方式被引用。
<item>
表示單一或多個 數量的字串。其中的值可以是其它字串的引用。
屬性:
quanitty:
關鍵詞。數量表徵的值,由此確定引用哪個字串。下面是關於不同的值 的
下面舉個例說明:
在res/values/strings.xml的檔案
<span style="font-size:18px;"><?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></span>
在res/values-pl/strings.xml的檔案
<span style="font-size:18px;"><?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></span>
代碼引用:
<span style="font-size:18px;">int count = getNumberOfsongsAvailable();Resources res = getResources();String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);</span>
注意:在使用getQuantityString()方法時,如果你引用的字串包含%d的字串格式,你需要向方法內傳輸兩次count。用上面的例子來說明,你第一次傳入的參數count是為plural提供數量quantity作判斷的,你第二次傳入的count是插入到%d的預留位置的。
android中對字串的複數處理方法