【问题标题】:Wrong argument type for formatting argument格式化参数的参数类型错误
【发布时间】:2021-04-15 14:50:37
【问题描述】:

我使用temp_out.setText(response.body().getCurrent().getTemp() + " ℃"); 之类的代码从天气 API 获取数据,但出现两个 lint 错误:

不要将显示的文本与设置的文本连接起来。仅使用资源占位符。

setText 中的字符串文字无法翻译。请改用 Android 资源。

所以我在这里搜索了此站点上的类似错误,并在此处找到了部分解决方案https://stackoverflow.com/a/35053689/13899010, 我使用这个是因为我不想使用资源字符串来更改显示的数据。将此添加到 String.xml: <string name="blank">%d</string> 然后将我的代码更改为:

temp_out.setText(getString(R.string.blank, response.body().getCurrent().getTemp() + " ℃"));

现在我收到此错误Wrong argument type for formatting argument '#1' in blank: conversion is 'd', received string (argument #2 in method call)。 我看到了类似的问题Android Studio "Wrong argument type for formatting Error" in String.format(),但他的解决方案对我不起作用。请问这个怎么解决?

【问题讨论】:

  • 我认为您可以在添加空白字符串之前忽略上面引用的前两行。因为这只是告诉您应该使用字符串资源而不是硬编码字符串。但是如果你想使用那个空白,那么你应该这样做: %2$d ℃
  • @SlothCoding 现在我得到:错误的参数计数,格式字符串空白需要 2,但格式调用提供 1
  • 我不知道你回复的类型,我猜那是一个字符串。只需使用 %s 就可以了。
  • 我没有看到下面的答案,对不起。

标签: java android string android-studio textview


【解决方案1】:

确保response.body().getCurrent().getTemp()返回一个int,如果它是一个字符串,则在字符串blank中使用%s

您可以尝试以下方法之一

<string name="blank">%d Celsius</string>

//invoking as follows
getString(R.string.blank, response.body().getCurrent().getTemp())
temp_out.setText("${response.body().getCurrent().getTemp()} Celsius")

【讨论】:

  • 在字符串空白中使用 %s 对我有用,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2016-07-08
  • 2016-09-14
  • 2014-03-28
  • 2014-01-14
  • 1970-01-01
  • 2013-05-05
相关资源
最近更新 更多