从加载XML整数数组整数、数组、加载、XML

2023-09-08 09:19:54 作者:煮酒问寒秋

我有一个XML文件中的一个整数数组如下:

I have an integer array in an xml file as follows

<integer-array name="myArray">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
    <item>@drawable/pic4</item>
</integer-array>

在code,我试图加载这个数组

In the code, I am trying to load this array

int[] picArray = getResources().getIntArray(R.array.myArray);

预期的结果是

The expected result is

R.drawable.pic1, R.drawable.pic2,R.drawable.pic3

,而是它是未来与所有值的数组为零

but instead it is coming with an array with all values as zero

谁能告诉我什么是错?

推荐答案

您需要获得与ID的图像阵列。 也许这篇文章帮助你。这样一来,code,你可能需要:

You need to get an array with id's of your images. Probably this article helps you. And so the code you probably need:

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);
  }
}
 
精彩推荐