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

Format string XXX is not a valid format string so it should not be passed to String.format

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

<string name="create_group_select_people">Select up to %1$d people!</string>

这是从片段中调用的:

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

但我收到错误:

Format string 'create_group_select_people' is not a valid format string so it should not be passed to String.format

我不明白哪里出了问题?当我启动应用程序时 - 它会直接显示 "Select up to %1$d people!"

您可能缺少字符串的格式化方法class,如果您在 TextView 中设置它,正确的方法是:

textView.setText(String.format(getResources().getString(R.string.create_group_select_people), countMax));

您需要字符串格式化程序。请从

更改以下代码
 getResources().getString(R.string.create_group_select_people, countMax);

String temp =  String.format(getResources().getString(R.string.create_group_select_people), countMax);

更多详细信息refer

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

  1. 清理项目
  2. 检查多语言文件
  3. 或者像其他人说的那样使用String.format

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

<string name="some_text" formatted="true">
    Use for String.format method. Parameter one: %s1
</string>

并这样使用:

String.format(context.getString(R.string.some_text,"value 1"))

或者这样:

context.getString(R.string.some_text,"value 1"))

注意:只有带占位符的字符串才应将格式化标志设置为 true

尝试执行 'clean project',然后关闭并重新打开 Android Studio。

为我修复了它,它看起来像是一些 Android Studio /Lint 的小错误。

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

创建一个函数并将您的代码放入其中,并在函数之前添加此 @SuppressLint("StringFormatInvalid")。希望对你有帮助。

为了可能找到此主题的其他人,出现此警告的一个可能原因是您在字符串资源文件中定义了多种语言,但您没有在其中的一种或多种语言中指定格式参数。

例如,如果您的 values 文件夹中有一个 strings.xml,并且您的 values-es 文件夹中有另一个 strings.xml,但您只将格式参数添加到 strings.xml你的值文件夹,然后将触发警告,因为在你的值-es 文件夹中 strings.xml 的字符串资源中缺少格式参数。

要使字符串的格式正确:

String.format(Locale.ENGLISH, itemView.context.getString(R.string.XXX), "%17") 

另外,特殊字符不必干扰参数的注入。为此,请考虑特殊字符 exhaust outlets

来自<string name="XXX">% %1$s</string>

<string name="XXX">%1$s</string>

最后 XXX 是“%17”

祝你好运。

Source

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

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

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

在我的例子中,通过重启使缓存无效没有帮助,但在其他语言环境中使用一致的格式参数(例如 %s)解决了这个问题。我希望这对以后的人有所帮助。

我遇到了同样的问题,但它的来源不同。我的应用程序有一些语言,在一种翻译中没有“%”,而是一个“$”符号。它仍然有效,除了在这种特定语言中,我在使用字符串的相应行收到了这个提示。

如果它显示红色错误,然后像这样添加字符串值,它将起作用。

如果你想要字符串格式:

   <string name="msg_token_fmt" formatted="true"> %s
</string>

如果你想要float格式float:

<string name="msg_token_fmt" formatted="true"> %f
</string>

如果你想要数字格式:

  <string name="msg_token_fmt" formatted="true"> %d
    </string>

只需添加 <?xml version="1.0" encoding="utf-8"?> 作为 strings.xml

的第一行

Android 2021.2.1 补丁 1 仍有问题 无论如何,项目构建和运行正常,在清理、重建、使缓存失效后,对我来说没有任何真正改变。

设法消除了这样的警告


                    String msg = String.format(String.valueOf(R.string.msg_token_fmt), token);