@drawable/pic1<...">

Loading an Integer array from xml

I have an integer array in an 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 code I try to load this array

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

Expected Result

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

but instead it goes with an array with all values ​​as zero

Can someone tell me what is wrong?

+3
source share
4 answers

You need to get an array with the identifier of your images. Perhaps this article will help you. And therefore, the code that 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);
  }
}
+2
source

Found this 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]));

And the xml file resource can be:

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

, ?

:

<?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 , ?

EDIT: , . , .

+2
source

Just make it a regular array of resources. You can do it as follows:

<?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>

Then do not int [], just enter TypedArray as follows:

TypedArray icons = getResources().obtainTypedArray(R.array.icons);

and get it using

imageview.setImageDrawable(mIcons.getDrawable(position));
+1
source

Source: https://habr.com/ru/post/1780314/


All Articles