简体   繁体   中英

Get Layouts using integer-array Android

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM