Skip to main content

Command Palette

Search for a command to run...

How to Declare Variables in Android String Resources?

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

Updated
2 min read
How to Declare Variables in Android String Resources?
V

I'm a self-taught hobbyist Android developer who loves to build projects and share valuable tips for new Android developers.

Feel free to comment, share or connect with me!

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.

Android App Dev

Part 41 of 47

Discover helpful tips and tricks for Android app development and Jetpack Compose through my personal journey and experience.

Up next

Replace fragment tag with FragmentContainerView Causing Runtime Error

Because it fails to find navigation controller in your activity class