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

标签 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

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

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

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

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

那么为什么我会收到此错误?

最佳答案

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

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

关于android - 格式化字符串参数计数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667891/

相关文章:

c# - ConfigurationManager.ConnectionStrings 从 machine.config 返回额外的连接字符串

android - 在 android 中的 ListView 中单击按钮时出错

android - 在 Scala 中重写 Java 构造函数

javascript - react-native `keyboardShouldPersistPanGesture` 事件,防止键盘在快速滑动事件中消失

c - 是什么导致我的打印语句产生不同的结果?

java - 用于选择字符出现奇数次的字符串的正则表达式

android - 尝试调试 flutter 应用程序时 AVC 被拒绝

android - 从最近的应用程序关闭应用程序时服务停止

xslt - 编写 XPath 查询以根据属性和内容匹配元素

python - 将重复变量插入字符串