DEV Community

Cover image for How to Declare Variables in Android String Resources?
Vincent Tsen
Vincent Tsen

Posted on • Updated on • Originally published at vtsen.hashnode.dev

How to Declare Variables in Android String Resources?

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

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Originally published at https://vtsen.hashnode.dev.

Top comments (0)