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

解決 strings.xml 格式化佔位符錯誤:Multiple substitutions specified in non-positional format

編輯:關於 Android 程式設計

今天有位 Android 新手在使用 strings.xml 進行格式化時,遇到了佔位符報錯:Multiple substitutions specified in non-positional format; did you mean to add the formatted="false" attribute?,前來請教如何解決。這是一個非常典型的錯誤,本文就來徹底講清楚它的成因與解法。

一、錯誤描述

具體的錯誤信息如下:

Error:(16) Multiple substitutions specified in non-positional format;
did you mean to add the formatted="false" attribute?
Error:(16) Unexpected end tag string
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: ... aapt.exe' finished with non-zero exit value 1
Information:BUILD FAILED

二、問題原因

查看 strings.xml 源碼後發現,報錯的那一行是這樣寫的:

游戲%s,作者:%s

仔細檢查後發現,問題正是出在 string 中的兩個 %s。當一個字符串裡出現多個格式化佔位符時,Android 要求使用「位置化」的寫法,也就是把 %s 改成 %1$s 這樣帶序號的形式,否則 aapt 在編譯資源時就會報錯。

三、解決錯誤

把原來的寫法:

游戲%s,作者:%s

改為帶位置序號的形式:

游戲%1$s,作者:%2$s

然後重新編譯,即可成功通過。

小貼士:位置化佔位符不僅能解決編譯報錯,還有一個實用好處——在後續的代碼調用中,你可以自由調整參數的傳入順序而不影響顯示結果,這在同時進行多語言翻譯時尤為方便。另一種替代方案是在 string 標籤上添加 formatted="false" 屬性,但這種做法會關閉整個字符串的格式化解析,一般不如位置化佔位符推薦。

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