用2.3的SDK編譯了一下之前正常的項目,發現在資源文件中%地方會有錯誤。轉一篇相關的文帖。
-----------------------------------------------------------
前段時間更新了ADT和Android SDK 2.3,更新後發現自己2.2下編譯的很好的項目出現了問題,錯誤詳細內容爲:
Multiple annotations found at this line:
- error: Multiple substitutions specified in non-positional format; did you mean to add the formatted="false"
attribute?
- error: Unexpected end tag string
反覆檢查後發現是string.xml中的 % 導致編譯失敗,
去Google的Android開發者討論組查看關於這個問題的討論 後看到了Xavier Ducrohet大神的回覆,說這是由於新的SDK採用了新版本的aapt(Android項目編譯器),這個版本的aapt編譯起來會比老版本更加的嚴格,然後在Android最新的開發文檔的描述String的部分,已經說明了 如何去設置 %s 等符號,下面是文檔片段:
If you need to format your strings using String.format(String, Object...) , then you can do so by putting your format arguments in the string resource. For example, with the following resource:
如果你需要使用 String.format(String, Object...) 來格式化你的字符串,你可以把格式化參數放在你的字符串中,參見下面的例子:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguements from your application like this:
在這個例子中,這個格式化的字符串有2個參數, %1$s是個字符串 %2$d 是個浮點數,你可以在你的程序中按照下面的方法來根據參數來格式化字符串:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
那麼根據例子上說的我需要把%s換成%1$s才行了,修改後編譯通過,程序成功啓動。
問題補充:
有讀者問如何在<string></string>中使用%號
有兩個辦法可供選擇
最後稍微延伸一下這個格式化變化的原因: 大神Bob Kerns 覺得當前Java的格式化字符串方式可讀性不好(我也有同感),然後就寫了篇博文來提出他認爲的最好的方式,
http://bobkerns.typepad.com/bob_kerns_thinking/2010/12/dear-java-better-text-formatting-please.html
顯然,Android開發團隊認可了他的建議