轉自:http://blog.csdn.net/huangyabin001/article/details/37651165
摘要:
這是Android4.3Mms源碼中的strings.xml的一段代碼:
<!--Settings item desciption for integer auto-delete sms message limit -->
<string name="pref summary delete limit"><xliff:g id="count">%1$s</xliff:g>messages per conversation</String>
在這裡google的工程師們使用了<xliff:g >标簽,這個标簽主要在動态插入内容時候使用,有點類似于占位符的作用。這裡我們簡單介紹一下<xliff:g>。
簡介:
xliff是XML Localization Interchange File Format的縮寫,也就是XML本地化資料交換格式的意思。配合string結點一起使用,用于動态設定某些值。
一,在strings.xml檔案中定義的方法:
常用的屬性:
id:目前xliff結點的唯一辨別。
屬性example表示舉例說明,可選屬性。
Java 語言的格式化輸出使用示例:
StringBuilder sb = new StringBuilder(); // Send all output to the Appendable object sb Formatter formatter = new Formatter(sb, Locale.US); // Explicit argument indices may be used to re-order output. formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d") // -> " d c b a" // Optional locale as the first argument can be used to get // locale-specific formatting of numbers. The precision and width can be // given to round and align the value. formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); // -> "e = +2,7183" // The '(' numeric flag may be used to format negative numbers with // parentheses rather than a minus sign. Group separators are // automatically inserted. formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta); // -> "Amount gained or lost since last statement: $ (6,217.58)"
格式字元串文法:
産生格式化輸出的每個方法都需要格式字元串 和參數清單。格式字元串是一個
String
,它可以包含固定文本以及一個或多個嵌入的格式說明符。請考慮以下示例:
Calendar c = ...; String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
此格式字元串是 format 方法的第一個參數。它包含三個格式說明符 "%1$tm"、"%1$te" 和 "%1$tY",它們指出應該如何處理參數以及在文本的什麼地方插入它們。格式字元串的其餘部分是包括"Dukes Birthday: " 和其他任何空格或标點符号的固定文本。參數清單由傳遞給位于格式字元串之後的方法的所有參數組成。在上述示例中,參數清單的大小為
1,由對象
Calendar
c 組成。
- 正常類型、字元類型和數值類型的格式說明符的文法如下:
%[argument_index$][flags][width][.precision]conversion
可選的 argument_index 是一個十進制整數,用于表明參數在參數清單中的位置。第一個參數由 "1$" 引用,第二個參數由 "2$" 引用,依此類推。
可選 flags 是修改輸出格式的字元集。有效标志集取決于轉換類型。
可選 width 是一個非負十進制整數,表明要向輸出中寫入的最少字元數。
可選 precision 是一個非負十進制整數,通常用來限制字元數。特定行為取決于轉換類型。
所需 conversion 是一個表明應該如何格式化參數的字元。給定參數的有效轉換集取決于參數的資料類型。
- 用來表示日期和時間類型的格式說明符的文法如下:
%[argument_index$][flags][width]conversion
可選的 argument_index、flags 和 width 的定義同上。
所需的 conversion 是一個由兩字元組成的序列。第一個字元是 't' 或 'T'。第二個字元表明所使用的格式。這些字元類似于但不完全等同于那些由 GNUdate 和 POSIXstrftime(3c) 定義的字元。
- 與參數不對應的格式說明符的文法如下:
%[flags][width]conversion
可選 flags 和 width 的定義同上。
所需的 conversion 是一個表明要在輸出中所插内容的字元。
二,在java代碼中動态的方法:
getResources().getString(int id,Object...formatArgs);
下面貼出
Android官方問當中相關的方法:
public String getString(int id, Object... formatArgs) throws NotFoundException {
String raw = getString(id);
return String.format(mConfiguration.locale, raw, formatArgs);
}
id:字元串資源ID;
formatArgs:将用于替換格式的參數;從return語句中可以看到,這裡調用了String的format方法,
http://cn.bing.com/dict/search?q=%E5%B0%86&FORM=BDVSP6jdk文檔中給出的解釋是格式字元串中由格式說明符引用的參數。如果還有格式說明符以外的參數,則忽略這些額外的參數。參數的數目是可變的,可以為
0。參數的最大數目受Java Virtual Machine Specification所定義的java數組最大次元的限制。有關null參數的行為依賴于轉換。