2023年9月23日 星期六

【Android】 strings.xml (慢更)


格式化字串

多個參數

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

var text = getString(R.string.welcome_messages, username, mailCount)

字串集合 <plurals>

字串集合,其中一個字串會根據數量提供。包含一或多個 <item> 元素。

屬性:

name
「字串」。一對字串的名稱。系統會把此名稱當做資源 ID。

 舉例 (導覽與返回堆疊 (android.com)) :

<plurals name="cupcakes">
    <item quantity="one">%d cupcake</item>
    <item quantity="other">%d cupcakes</item>
</plurals>

在 Kotlin 程式碼中呼叫:

getQuantityString(R.plurals.cupcakes, 1, 1) 會傳回 1 cupcake 字串

getQuantityString(R.plurals.cupcakes, 6, 6) 會傳回 6 cupcakes 字串

getQuantityString(R.plurals.cupcakes, 0, 0) 會傳回 0 cupcakes 字串

注意:呼叫 getQuantityString() 時,您必須傳入數量兩次,因為第一個數量參數用於選取正確的複數字串。第二個數量參數則用於實際字串資源的 %d 預留位置。

參考資料

0 comments:

張貼留言