使用整数数组Android获得布局

时间:2021-09-11 16:06:35

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

我想从我的java文件中检索布局的地址。但是,我得到的是0。

res/values/worlds.xml:

res /价值/ 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:

以及我用来获取数组的Java代码:

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

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

但是Java代码给了我一个0。

1 个解决方案

#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 :

不是整数类型。因此,在xml中使用数组来存储项目和obtainTypedArray,以便从xml获取项目数组,然后使用getResourceId将布局id传递给setContentView:

res/values/worlds.xml:

res /价值/ 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();

#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 :

不是整数类型。因此,在xml中使用数组来存储项目和obtainTypedArray,以便从xml获取项目数组,然后使用getResourceId将布局id传递给setContentView:

res/values/worlds.xml:

res /价值/ 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();