是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
当前回答
你可以使用MessageFormat:
<string name="customer_address">Wellcome: {0} {1}</string>
在Java代码中:
String text = MessageFormat(R.string.customer_address).format("Name","Family");
火力等级1:
https://developer.android.com/reference/java/text/MessageFormat.html
其他回答
你可以使用MessageFormat:
<string name="customer_address">Wellcome: {0} {1}</string>
在Java代码中:
String text = MessageFormat(R.string.customer_address).format("Name","Family");
火力等级1:
https://developer.android.com/reference/java/text/MessageFormat.html
在res /价值/ string.xml
<resources>
<string name="app_name">Hello World</string>
<string name="my_application">Application name: %s, package name: %s</string>
</resources>
Java代码
String[] args = new String[2];
args[0] = context.getString(R.string.app_name);
args[1] = context.getPackageName();
String textMessage = context.getString(R.string.my_application,(Object[]) args);
如果你想写百分比(%),复制它:
<string name="percent">%1$d%%</string>
label.text = getString(R.string.percent, 75) // Output: 75%.
如果你只写%1$d%,你会得到一个错误:格式字符串'percent'不是一个有效的格式字符串,所以它不应该被传递给string . Format。
或者使用格式化=false"代替。
问题的直接Kotlin解决方案:
strings.xml
<string name="customer_message">Hello, %1$s!\nYou have %2$d Products in your cart.</string>
kotlinActivityORFragmentFile.kt:
val username = "Andrew"
val products = 1000
val text: String = String.format(
resources.getString(R.string.customer_message), username, products )
一直在寻找同样的方法,最后找到了下面这个非常简单的方法。最好的:它可以开箱即用。 1. 修改你的字符串资源:
<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have
<xliff:g name="count">%d</xliff:g> new messages.</string>
2. 使用字符串替换:
c.getString (R.string.welcome_messages、名称、数);
其中c是上下文,名称是一个字符串变量和计数你的int变量
你需要包括
<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">
在res/strings.xml中。 对我有用。:)