4
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="level_2">
        <item name="first">some value</item>
        <item name="second">some value</item>
        <item name="third">some value</item>
    </array>
</resources>

-

int currentLevel = 2;        
TypedArray testArray = getResources().obtainTypedArray(R.array.level_2);
int firstValue = testArray.getInt(0,0);

I'm trying to dynamically set the resource (array) to use based on some data. For example, I have arrays for each level like the one above. Instead of using the resource id R.array.level_2 in obtainTypedArray() I'd like to use the value of the int currentLevel in the example above.

So, some way of doing something like: obtainTypedArray("R.array.level_"+level)

Any ideas? Thanks!

1 Answer 1

3

You should use Context.getResources().getIdentifier(); Method, at the below, can be called in any activity via getStrArrWithId("level_" + level, getApplicationContext());

public String [] getStrArrWithId (String id, Context context) {
    int arrId = context.getResources().getIdentifier(id, "array", context.getPackageName());
    String[] strArr = context.getResources().getStringArray(arrId);
    return strArr;
}
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.