Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

strings.xml 中的百分號之困:三種解法

報錯現場

在 strings.xml 中寫入帶百分號的內容:

<string name="myurl">https://code.dd.com/rr?q=%rr.55</string>

ADT 立刻報出:

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

原因

Android 的字符串資源默認按 String.format 的規則處理,% 是格式化占位符的起始符。當出現無法解析的 % 時,解析器既讀不懂占位符,又錯誤地把後續內容當成標簽,於是連帶報出「標簽未閉合」的第二條錯誤。

三種解法

1. 用兩個百分號轉義

<string name="myurl">https://code.dd.com/rr?q=%%rr.55</string>

2. 用反斜線轉義

<string name="myurl">https://code.dd.com/rr?q=\%rr.55</string>

3. 關閉格式化

依報錯提示,若該字符串本來就不需要格式化,直接加屬性:

<string name="myurl" formatted="false">https://code.dd.com/rr?q=%rr.55</string>

該選哪一個

純 URL、片段文本這類不涉及占位符的內容,用 formatted="false" 語義最清晰;若同一條字符串裡既有普通百分號又有 %1$s 之類的位置化占位符,則必須用 %% 表示字面百分號,並保持占位符帶位置序號,否則仍會觸發第一條錯誤。

Copyright © Linux教程網 All Rights Reserved