2

I am trying to create a R.string.[variable] in a for loop to save me lots of lines of code.

I tried this, but it doesn't work

inside strings.xml, I have these

<string name="posA1">Position A 1</string>
<string name="posA2">Position A 2</string>
<string name="posA3">Position A 3</string>
...etc

main.java

    for (int j=0; j<10; j++) {
        ...
        string = R.string. + "posA" + j;
        ...
    }

How can I do this?

1 Answer 1

5

What about an array?

<?xml version="1.0" encoding="utf-8"?>
<resources>  
<string-array name="testArray">  
    <item>first</item>  
    <item>second</item>  
    <item>third</item>  
    <item>fourth</item>  
    <item>fifth</item>
</string-array>
</resources>

and then in your code:

String[] myArray = getResources().getStringArray(R.array.testArray);
for(int i = 0; i<myArray.length(); i++) {
    String string = myArray[i];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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