Loading Integer Array from xml

后端 未结 4 531
猫巷女王i
猫巷女王i 2020-12-21 03:57

I have an integer array in an xml file as follows


    @drawable/pic1
    @drawabl         


        
相关标签:
4条回答
  • 2020-12-21 04:18

    Just make it a normal resource array. You could do it like this:

    <?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 don't make a int[] just make a TypedArray like this:

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

    and get it with:

    imageview.setImageDrawable(mIcons.getDrawable(position));
    
    0 讨论(0)
  • 2020-12-21 04:35

    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);
      }
    }
    
    0 讨论(0)
  • 2020-12-21 04:42

    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 resources xml file could 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>
    
    0 讨论(0)
  • 2020-12-21 04:43

    It looks like you might be talking about typed arrays?

    if so a typed array should look like this:

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

    Can you show us your actual xml file so we can help you?

    EDIT: Yeah those are not integers. make it a resource array if you want to store resources.

    0 讨论(0)
提交回复
热议问题