1

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Yes, I can do this, just didn't think of it.
1

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().

5 Comments

Thank you. I would mark this as the anser but Kurru answered first.
Uh, not really. You see that mine came 3 minutes earlier (look at the "answered n mins ago").
Why would you use a interger array? Would a string array not be better?
@Kurru: Why load all the strings into memory? That's wasteful. Integers are much more compact, and you don't have to reload the strings if the user decides to change the language. Of course, if it's only a handful of strings, and if you use them A LOT, then it's faster to cache them into a string array.
If they're hand typed into the program I doubt theres any significant waste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.