是否可能在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

格式和样式

是的,请参阅下面的字符串资源:格式和样式

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);

基本用法

注意,getString有一个重载,它使用字符串作为格式化字符串:

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

复数

如果你需要处理复数,使用这个:

<plurals name="welcome_messages">
    <item quantity="one">Hello, %1$s! You have a new message.</item>
    <item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>

第一个mailCount参数是用来决定使用哪种格式(单复数),其他参数是你的替换:

Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);

有关更多细节,请参阅字符串资源:复数。

在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);

Kotlin版本的公认答案…

val res = resources
val text = String.format(res.getString(R.string.welcome_messages), username, mailCount)

是的!你可以不写任何Java/Kotlin代码,只使用XML,使用我创建的这个小库,它在构建时这样做,所以你的应用程序不会受到它的影响:https://github.com/LikeTheSalad/android-stem

使用

你的字符串:

<resources>
    <string name="app_name">My App Name</string>
    <string name="welcome_message">Welcome to ${app_name}</string>
</resources>

构建后生成的字符串:

<!-- Auto generated during compilation -->
<resources>
    <string name="welcome_message">Welcome to My App Name</string>
</resources>