格式化字符串参数计数错误

时间:2015-09-19 11:52:05

标签: android string

我的string.xml中有一个字符串:

<string name="date_time_short">%2$d.%2$d. %1$s %2$d:%2$d</string>

现在我想从代码中设置值:

String.format(context.getResources().getString(R.string.date_time_short), day, month, at, hour, minute);

但我得到错误:

Wrong argument count, format string date_time_short requires 2 but format call supplies 5

因此%1$s似乎存在代表字符串的问题。至少这是写在文档here

  

如果需要使用String.format(String,Object ...)格式化字符串,则可以将格式参数放在字符串资源中。例如,使用以下资源:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
  

在此示例中,格式字符串有两个参数:%1 $ s是字符串,%2 $ d是十进制数。您可以使用应用程序中的参数格式化字符串,如下所示:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

那我为什么会收到这个错误?

2 个答案:

答案 0 :(得分:6)

例如,%1 $ s中的数字表示Object ...参数中的索引。所以在你的例子中,字符串的正确定义是:

<string name="date_time_short">%1$d.%2$d. %3$s %4$d:%5$d</string>

答案 1 :(得分:1)

试试这个<string name="date_time_short">%1$s.%2$s. %3$s %4$s:%5$s</string>