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

例子:

PLACEHOLDER1一些字符串


当前回答

问题的直接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解决方案:

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)

你可以使用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

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

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

在Kotlin中,你只需要像这样设置你的字符串值:

<string name="song_number_and_title">"%1$d ~ %2$s"</string>

在你的布局上创建一个文本视图:

<TextView android:text="@string/song_number_and_title"/>

如果你使用Anko,那么在你的代码中这样做:

val song = database.use { // get your song from the database }
song_number_and_title.setText(resources.getString(R.string.song_number_and_title, song.number, song.title))  

您可能需要从应用程序上下文中获取资源。