Member-only story

How to Declare Variables in Android String Resources?

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

Vincent Tsen
2 min readJan 14, 2022

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

--

--

No responses yet