格式字符串XXX不是有效的格式字符串,因此不应将其传递给String.format

Wac*_*oon 23 java string android android-resources

我有android应用程序和资源中的这个字符串:

<string name="create_group_select_people">Select up to %1$d people!</string>
Run Code Online (Sandbox Code Playgroud)

这是从片段调用的:

Integer countMax = 5; //also tried just "int" - nothing changed
getResources().getString(R.string.create_group_select_people, countMax);
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误:

Format string 'create_group_select_people' is not a valid format string so it should not be passed to String.format
Run Code Online (Sandbox Code Playgroud)

我无法理解什么是错的?当我启动应用程序时 - 它按字面意思显示"选择最多%1美元的人!"

小智 25

我只是复制了代码,效果很好.所以你可能需要检查其他地方,这是我的建议.

  1. 干净的项目
  2. 检查多语言文件
  3. 或者像其他人一样使用String.format

  • 干净的项目没有帮助,项目中没有多语言文件,String.format给出了同样的错误,但是`Invalidate Caches and restart`工作,不知何故错误消失了,现在工作正常 (22认同)
  • 我不确定其他人的情况,但对我来说,百分比(%)符号存在问题,可能与 Unicode 有关。应该有一个小符号(https://www.compart.com/en/unicode/U+FE6A)而不是大符号(https://www.compart.com/en/unicode/U+0025)。希望这可以帮助 :) (2认同)

Mig*_*Slv 13

在资源中将参数格式化为true:

<string name="some_text" formatted="true">
    Use for String.format method. Parameter one: %s1
</string>
Run Code Online (Sandbox Code Playgroud)

并使用这种方式:

String.format(context.getString(R.string.some_text,"value 1"))
Run Code Online (Sandbox Code Playgroud)

或者这样:

context.getString(R.string.some_text,"value 1"))
Run Code Online (Sandbox Code Playgroud)

注意:格式化标志应仅对具有占位符的字符串设置为true


sHa*_*BoY 11

如果您在多个字符串文件(翻译)中有相同的字符串,但其中一个没有正确的格式,例如缺少将用于放置参数的“%s”或“%1$s”,则会显示此错误在下面的行中通过(例如:“countMax”)。

getResources().getString(R.string.create_group_select_people, countMax)

因此,在尝试上述任何其他答案之前,请先检查一下。


smi*_*ty1 8

为了其他人可能会发现此线程,此警告的一个可能原因是您在字符串资源文件中定义了多种语言,并且您没有在其中一个或多个中指定格式参数。

例如,如果您的 values 文件夹中有一个 strings.xml,您的 values-es 文件夹中有另一个 strings.xml,但您只向 values 文件夹中的 strings.xml 添加了格式参数,则将触发警告,因为您的 values-es 文件夹中 strings.xml 的字符串资源中缺少格式参数。


Ber*_*mpl 5

试试看File -> Invalidate Caches / Restart...,它为我解决了问题。