我的字符串中有一个字符串string.xml:
<string name="date_time_short">%2$d.%2$d. %1$s %2$d:%2$d</string>
Run Code Online (Sandbox Code Playgroud)
现在我想从代码中设置值:
String.format(context.getResources().getString(R.string.date_time_short), day, month, at, hour, minute);
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
Wrong argument count, format string date_time_short requires 2 but format call supplies 5
Run Code Online (Sandbox Code Playgroud)
所以它似乎有一个问题,%1$s它代表一个字符串.至少这是写在这里的文档中
如果需要使用String.format(String,Object ...)格式化字符串,则可以通过将格式参数放在字符串资源中来实现.例如,使用以下资源:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
Run Code Online (Sandbox Code Playgroud)
在此示例中,格式字符串有两个参数:%1 $ s是字符串,%2 $ d是十进制数.您可以使用应用程序中的参数格式化字符串,如下所示:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Run Code Online (Sandbox Code Playgroud)
那么为什么我会收到这个错误?
例如,%1 $ s中的数字表示Object ...参数中的索引.所以在你的例子中,字符串的正确定义是:
<string name="date_time_short">%1$d.%2$d. %3$s %4$d:%5$d</string>
Run Code Online (Sandbox Code Playgroud)