是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?
例子:
PLACEHOLDER1一些字符串
当前回答
Kotlin版本的公认答案…
val res = resources
val text = String.format(res.getString(R.string.welcome_messages), username, mailCount)
其他回答
一直在寻找同样的方法,最后找到了下面这个非常简单的方法。最好的:它可以开箱即用。 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中。 对我有用。:)
在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"代替。
补充回答
当我第一次在接受的答案中看到%1$s和%2$d时,它毫无意义。这里有更多的解释。
它们被称为格式说明符。在xml字符串中,它们的形式是
%[parameter_index$][format_type]
%: The percent sign marks the beginning of the format specifier. parameter index: This is a number followed by a dollar sign. If you had three parameters that you wanted to insert into the string, then they would be called 1$, 2$, and 3$. The order you place them in the resource string doesn't matter, only the order that you supply the parameters. format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones: s string d decimal integer f floating point number
例子
我们将创建以下格式化字符串,其中灰色部分以编程方式插入。
我妹妹玛丽12岁了。
string.xml
<string name="my_xml_string">My sister %1$s is %2$d years old.</string>
MyActivity.java
String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);
笔记
I could use getString because I was in an Activity. You can use context.getResources().getString(...) if it is not available. String.format() will also format a String. The 1$ and 2$ terms don't need to be used in that order. That is, 2$ can come before 1$. This is useful when internationalizing an app for languages that use a different word order. You can use a format specifier like %1$s multiple times in the xml if you want to repeat it. Use %% to get the actual % character. For more details read the following helpful tutorial: Android SDK Quick Tip: Formatting Resource Strings
在你的字符串文件中使用这个
<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)));