是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
当前回答
在你的字符串文件中使用这个
<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>
并在代码中相应地使用
coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
, rewardPoints.getConversion_rate(), getString(R.string.rs)));
其他回答
Kotlin版本的公认答案…
val res = resources
val text = String.format(res.getString(R.string.welcome_messages), username, mailCount)
当你想使用实际strings.xml文件中的参数而不使用任何Java代码时:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
<!ENTITY appname "WhereDat">
<!ENTITY author "Oded">
]>
<resources>
<string name="app_name">&appname;</string>
<string name="description">The &appname; app was created by &author;</string>
</resources>
这对跨资源文件不起作用,即变量必须复制到每个需要它们的XML文件中。
你可以使用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);
但是,你也应该阅读Elias Mårtenson关于Android复数处理“零”的回答。对某些值(如“零”)的解释存在问题。