dbm dbm - 1 month ago 10
Android Question

Reference one string from another string in strings.xml?

I would like to reference a string from another string in my strings.xml file, like below (specifically note the end of the "message_text" string content):

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="button_text">Add item</string>
<string name="message_text">You don't have any items yet! Add one by pressing the \'@string/button_text\' button.</string>
</resources>


I've tried the above syntax but then the text prints out the "@string/button_text" as clear text. Not what I want. I would like the message text to print "You don't have any items yet! Add one by pressing the 'Add item' button."

Is there any known way to achieve what I want?

RATIONALE:

My application has a list of items, but when that list is empty I show a "@android:id/empty" TextView instead. The text in that TextView is to inform the user how to add a new item. I would like to make my layout fool-proof to changes (yes, I'm the fool in question :-)

Answer

I think you can't. But you can "format" a string as you like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="button_text">Add item</string>
    <string name="message_text">You don't have any items yet! Add one by pressing the %1$s button.</string>
</resources>

In the code:

Resources res = getResources();
String text = String.format(res.getString(R.string.message_text),
                            res.getString(R.string.button_text));