我在xml文件中有一个整数数组,如下所示
<integer-array name="myArray">
<item>@drawable/pic1</item>
<item>@drawable/pic2</item>
<item>@drawable/pic3</item>
<item>@drawable/pic4</item>
</integer-array>
在代码中,我正在尝试加载此数组
int[] picArray = getResources().getIntArray(R.array.myArray);
预期结果是
R.drawable.pic1, R.drawable.pic2,R.drawable.pic3
但是它带有一个数组,所有值都为零
谁能告诉我出了什么问题?
答案 0 :(得分:11)
找到此solution:
TypedArray ar = context.getResources().obtainTypedArray(R.array.myArray);
int len = ar.length();
int[] picArray = new int[len];
for (int i = 0; i < len; i++)
picArray[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(picArray[i]));
资源xml文件可以是:
<resources>
<integer-array name="myArray">
<item>@drawable/pic1</item>
<item>@drawable/pic2</item>
<item>@drawable/pic3</item>
<item>@drawable/pic4</item>
</integer-array>
</resources>
答案 1 :(得分:2)
看起来你可能在谈论类型化数组?
如果这样,输入的数组应如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="icons">
<item>@drawable/home</item>
<item>@drawable/settings</item>
<item>@drawable/logout</item>
</array>
<array name="colors">
<item>#FFFF0000</item>
<item>#FF00FF00</item>
<item>#FF0000FF</item>
</array>
</resources>
您能告诉我们您的实际xml文件,以便我们为您提供帮助吗?
编辑:是的,这些不是整数。如果要存储资源,请将其设为资源数组。答案 2 :(得分:2)
您需要获取包含图片ID的数组。 可能this article可以帮助你。所以您可能需要的代码:
int[] picArray = new int[4];
for (int i = 1; i <=4; i++)
{
try
{
Class res = R.drawable.class;
Field field = res.getField("pic"+i);
picArray[i-1] = field.getInt(null);
}
catch (Exception e)
{
Log.e("MyTag", "Failure to get drawable id.", e);
}
}
答案 3 :(得分:1)
让它成为普通的资源数组。你可以这样做:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="icons">
<item>@drawable/home</item>
<item>@drawable/settings</item>
<item>@drawable/logout</item>
</array>
</resources>
然后不要让int []像这样制作一个TypedArray:
TypedArray icons = getResources().obtainTypedArray(R.array.icons);
并获得:
imageview.setImageDrawable(mIcons.getDrawable(position));