dynamic String using String.xml?

2019-01-02 16:20发布

Is it possible to have placeholders in string values in string.xml that can be assigned values at run time?

Example:

some string PLACEHOLDER1 some more string

9条回答
临风纵饮
2楼-- · 2019-01-02 17:07

You can use MessageFormat

<string name="customer_address">Wellcome: {0} {1}</string>

In Java code :

String text =MessageFormat(R.string.customer_address).format("Name","Family");

API level 1:

https://developer.android.com/reference/java/text/MessageFormat.html

查看更多
浪荡孟婆
3楼-- · 2019-01-02 17:09

In Kotlin you just need to set your string value like this:

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

Create a text view on your layout:

<TextView android:id="@+id/song_number_and_title"/>

Then do this in your code if you using 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))  

You might need to get your resources from the application context.

查看更多
心情的温度
4楼-- · 2019-01-02 17:12

However, you should also read Elias Mårtenson's answer on Android plurals treatment of “zero”. There is a problem with the interpretation of certain values such as "zero".

查看更多
登录 后发表回答