Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

strings.xml 出現百分號導致編譯失敗怎麼辦

編輯:關於 Android 程式設計

編輯 strings.xml 時,只要字串裡出現 %,就可能出現編譯錯誤。例如:

<string name="url">https://aa.cc.com/dd?g=%rasdf</string>

或是含有多個佔位符的寫法:

<string name="message_content">這裡是積分 %1s 積分,佔比 %2s %</string>

這時 aapt 會拋出類似以下的訊息:

error: Multiple substitutions specified in non-positional format;
did you mean to add the formatted="false" attribute?
error: Unexpected end tag string

根本原因很單純:Android 把字串中的 % 當成格式化佔位符的前綴,因此當它後面接的不是合法格式,或同時出現多個非位置化佔位符時,就會被判為錯誤。

三種解法

方法一:以兩個百分號表示一個

<string name="url">https://aa.cc.com/dd?g=%%rasdf</string>

方法二:使用跳脫字元

<string name="url">https://aa.cc.com/dd?g=\%rasdf</string>

方法三:關閉格式化

依照錯誤訊息的提示,如果這段字串本來就不需要格式化,直接在 <string> 標籤上加屬性即可:

<string name="url" formatted="false">https://aa.cc.com/dd?g=%rasdf</string>

該選哪一個

若字串日後會透過 String.format() 帶入參數,就必須保留佔位符語意,這時應使用方法一或方法二,並確認佔位符採用位置化寫法(%1$s、%2$s)。若純粹是一段含有 URL 或百分比符號的固定文案,方法三最直觀,能讓原始字串保持原貌不被改寫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved