Silvestri
Silvestri

Reputation: 87

Dynamically referencing a String in Strings.xml in Android

Say I have the following my strings.xml file:

<string name="string0">Lorem</string>
<string name="string1">ipsum</string>
<string name="string2">dolor</string>

In my activity an ID is set based on the clicking of a button. If the top button is clicked the id is 0, middle is 1 and bottom button is 2.

What would the syntax look like for referencing one of the three strings?

I know R.string.string0 works but I want to do something equivalent to:

R.string["string"+currentID]

where I derive the string to use based on the ID.

Just not sure what the syntax would look like in Java/Android.

Thanks in advance, Tony

Upvotes: 1

Views: 509

Answers (2)

Kurru
Kurru

Reputation: 14321

Could you not just use a string array in your resources instead of separate string entries?

Upvotes: 4

EboMike
EboMike

Reputation: 77722

That's a bad approach. It's slow. It'd be better to have an internal integer array with all the R.string IDs.

If you really insist on using a string-based approach, use Resources.getIdentifier().

Upvotes: 1

Related Questions