在strings.xml中使用占位符来存储运行时值,这种做法可行吗?

652

string.xml 中,是否可以使用占位符来表示字符串值,在运行时将其赋值?

例如:

一些字符串 PLACEHOLDER1 更多的字符串


可能是在strings.xml中引用另一个字符串的参考?的重复问题。 - Harish Gyanani
@HarishGyanani 不,这个比较旧,那个应该合并到这个里面。 - Danh
14个回答

1
在res/values/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

是的!您可以使用我创建的这个小型库,在不编写任何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>

0

这是一个直接用 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

已被接受的答案的 Kotlin 版本...

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

4
更加正确的方式是使用带参数的resources.getString(int, ... args)方法而不是使用String.format。 除了val关键字之外,这段代码中没有其他Kotlin特定的内容。请参阅msbodw001的答案。 - dant3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接