是否可能在string.xml中的字符串值中有占位符,可以在运行时分配值?

例子:

PLACEHOLDER1一些字符串


当前回答

但是,你也应该阅读Elias Mårtenson关于Android复数处理“零”的回答。对某些值(如“零”)的解释存在问题。

其他回答

在你的字符串文件中使用这个

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

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

一直在寻找同样的方法,最后找到了下面这个非常简单的方法。最好的:它可以开箱即用。 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中。 对我有用。:)

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>