在 string.xml
中,是否可以使用占位符来表示字符串值,在运行时将其赋值?
例如:
一些字符串 PLACEHOLDER1 更多的字符串
在 string.xml
中,是否可以使用占位符来表示字符串值,在运行时将其赋值?
例如:
一些字符串 PLACEHOLDER1 更多的字符串
<resources>
<string name="app_name">Hello World</string>
<string name="my_application">Application name: %s, package name: %s</string>
</resources>
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);
是的!您可以使用我创建的这个小型库,在不编写任何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>
这是一个直接用 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 )
已被接受的答案的 Kotlin 版本...
val res = resources
val text = String.format(res.getString(R.string.welcome_messages), username, mailCount)
resources.getString(int, ... args)
方法而不是使用String.format
。 除了val
关键字之外,这段代码中没有其他Kotlin特定的内容。请参阅msbodw001的答案。 - dant3