Android – loads an array of integers from XML

I have an array of integers in the XML file, as shown below

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

In the code, I'm 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

Instead, it takes an array with all values zero

Who can tell me what the problem is?

resolvent:

You need to get an array containing image ID. maybe this article will help you. So you may need code:

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>