Reference one string from another string in strings.xml?

dbm picture dbm · Jan 20, 2011 · Viewed 84.6k times · Source

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

Beeing Jk picture Beeing Jk · Oct 5, 2016

A nice way to insert a frequently used string (e.g. app name) in xml without using Java code: source

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE resources [
      <!ENTITY appname "MyAppName">
      <!ENTITY author "MrGreen">
    ]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>

UPDATE:

You can even define your entity globaly e.g:

res/raw/entities.ent:

<!ENTITY appname "MyAppName">
<!ENTITY author "MrGreen">

res/values/string.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
    <!ENTITY % ents SYSTEM "./res/raw/entities.ent">
    %ents;   
]>

<resources>
    <string name="app_name">&appname;</string>
    <string name="description">The &appname; app was created by &author;</string>
</resources>