创建资源id的整数数组

时间:2021-02-01 00:33:02

I have some images in my res/drawable folder. Let's say img1.png, img2.png and img3.png. I am currently creating an integer array of these image IDs in Java like this

我的res/drawable文件夹里有一些图片。假设img1。png、img2。png和img3.png。我目前正在用Java创建这些图像id的整数数组

int[] imgIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3};

Instead, is it possible to create an integer array in one of res/values files (say strings.xml) like this

相反,可以在res/values文件(比如strings.xml)中创建一个整数数组。

<integer-array name="img_id_arr">
    <item>@drawable/img1</item>
    <item>@drawable/img2</item>
    <item>@drawable/img3</item>
</integer-array>

and then access it in Java via getResources().getIntArray(R.array.img_id_arr)?

然后通过getResources().getIntArray(R.array.img_id_arr)访问它?

3 个解决方案

#1


61  

Use just "array" instead of "integer-array". See Typed Array in the developer guide.

使用“数组”而不是“整数数组”。请参阅开发人员指南中的类型化数组。

#2


44  

See XML integer array, resource references, getIntArray

参见XML整数数组、资源引用、getIntArray。

TypedArray ar = context.getResources().obtainTypedArray(R.array.my_array);
int len = ar.length();
int[] resIds = new int[len];
for (int i = 0; i < len; i++)
    resIds[i] = ar.getResourceId(i, 0);
ar.recycle();
// Do stuff with resolved reference array, resIds[]...
for (int i = 0; i < len; i++)
    Log.v (TAG, "Res Id " + i + " is " + Integer.toHexString(resIds[i]));

#3


1  

Make a LevelListDrawable. Although it is not exactly what you want, but pretty much achievable.

LevelListDrawable。虽然这并不是你想要的,但几乎是可以实现的。

#1


61  

Use just "array" instead of "integer-array". See Typed Array in the developer guide.

使用“数组”而不是“整数数组”。请参阅开发人员指南中的类型化数组。

#2


44  

See XML integer array, resource references, getIntArray

参见XML整数数组、资源引用、getIntArray。

TypedArray ar = context.getResources().obtainTypedArray(R.array.my_array);
int len = ar.length();
int[] resIds = new int[len];
for (int i = 0; i < len; i++)
    resIds[i] = ar.getResourceId(i, 0);
ar.recycle();
// Do stuff with resolved reference array, resIds[]...
for (int i = 0; i < len; i++)
    Log.v (TAG, "Res Id " + i + " is " + Integer.toHexString(resIds[i]));

#3


1  

Make a LevelListDrawable. Although it is not exactly what you want, but pretty much achievable.

LevelListDrawable。虽然这并不是你想要的,但几乎是可以实现的。