How to Declare Variables in Android String Resources?

To be referenced by another string resources to avoid duplicated hard-coded strings in different places.

ยท

2 min read

How to Declare Variables in Android String Resources?

Suppose you have 2 string resources app_name and about_text below, you have 2 duplicated hard-coded strings.

<resources>
    <string name="app_name">My App Name</string>
    <string name="about_text">My App Name</string>
</resources>

Reference Another String Resources

To get rid of duplicated hard-coded strings, what you can do is reference the app_name from the about_text.

<resources>
    <string name="app_name">My App Name</string>
    <string name="about_text">@string/app_name</string>
</resources>

But what if you have more complicated about_text like below?

<resources>
    <string name="app_name">My App Name</string>
    <string name="about_text">My App Name is an awesome app!</string>
</resources>

Use String Format

You can change the about_text to string format to allow the string to be constructed at run time.

<resources>
    <string name="app_name">My App Name</string>
    <string name="about_text">%s is an awesome app!</string>
</resources>

In code (in your activity class for example), you pass in the app_name string.

val aboutText = resources.getString(
    R.string.about_text,
    resources.getString(R.string.app_name))

Well, there is another better solution to use DOCTYPE! You don't need to pass in the string variable from code.

Use DOCTYPE resources ENTITY

The DOCTYPE resources ENTITY declaration like a variable. You can reference it from another string resources using &<entity_name>; syntax.

<!DOCTYPE resources [
    <!ENTITY app_name "My App Name">
    <!ENTITY another_name "Test 1 2 3">
    ]>

<resources>
    <string name="app_name">&app_name;</string>
    <string name="about_text">&app_name; is an awesome app!</string>
</resources>

P/S: If there is another way better than using DOCTYPE, please let me know.

Did you find this article valuable?

Support Vincent Tsen by becoming a sponsor. Any amount is appreciated!

ย