1

I would like to retrieve the layouts' address using a from my java file. However, what I get is 0.

res/values/worlds.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer-array
        name="world1">
        <item>@layout/lvl_1</item>
        <item>@layout/lvl_1</item>
    </integer-array>
</resources>

and the Java code which I use to get the array:

Resources res = getResources();
int[] layouts = res.getIntArray(R.array.world1);
setContentView(layouts[0]);

the Java code gives me a 0 on my Logcat though.

1

1 Answer 1

4
<item>@layout/lvl_1</item>  

is not type of Integer. so use array in xml to store items and obtainTypedArray in code for getting Array of items from xml then use getResourceId to pass layout id to setContentView as :

res/values/worlds.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array
        name="world1">
        <item>@layout/lvl_1</item>
        <item>@layout/lvl_1</item>
    </array>
</resources>

In code set layout as:

TypedArray layouts = getResources().obtainTypedArray(R.array.world1);
int layoutid=layouts.getResourceId(0, -1);
setContentView(layoutid);
layouts.recycle();
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly! Forgive me but, if I may add, is there any way to store this typed array to a <List>? I would want to use Collections.shuffle on the retrieved layouts' ids

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.