1

I'm currently doing Android development.

The class R (an automatically-generated class) has lots of 'global' values accessed from anywhere like so:

R.drawable.<file_name_ignoring_suffix>

I have lots of files named 'item_0.png', 'item_1.png', 'item_2.png' etc.

Is there an easy way to iterate through these items without putting them into an array first?

My current implementation:

int[] itemResources = { R.drawable.item_0, R.drawable.item_1, R.drawable.item_2,
                        R.drawable.item_3, R.drawable.item_4, R.drawable.item_5  };

... then iterating through the array.

This works well, but it isn't particularly maintainable, and gets laborious when I have many items.

Any ideas?

Tim
  • 35,413
  • 11
  • 95
  • 121
Will Manson
  • 167
  • 1
  • 4
  • 12
  • "*global elements*"? To me it's not a specific terminology. – Lion Jul 10 '12 at 02:14
  • @Lion I used quote symbols around the word 'global' since I use the term loosely. I'm aware that there are no such things as global variables in Java, but I'm referring to variables declared by `public final static`. – Will Manson Jul 10 '12 at 02:23

3 Answers3

2

You could certainly use reflection to get the list of fields of R.drawable. It's kind of hacky, but it might work for you.

Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • Here is the relevant SO question: http://stackoverflow.com/questions/2538380/how-to-display-list-of-resource-drawables This does what Keith is referring to as "use reflection". – hopia Jul 10 '12 at 02:07
  • Very intriguing answer. I'm reading the article as we speak. @hopia This answer is interesting, also. To make it work for my situation, I could manipulate the strings provided by f.getName() to identify which 'set' of images the image in question belongs to (since I have 'items', 'coins', 'powerups' etc.) Thanks, both of you! – Will Manson Jul 10 '12 at 02:16
1

I think, there is no easy way to do it. Here is small code i tried to get the drawables.

    R.drawable d = new R.drawable();
    try {
        for (Field fld : declaredFields) {
            Integer id = fld.getInt(d);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);
            if (bitmap != null)
                Log.d("tag", "success");
            else
                Log.d("tag", "failed");
        }
    } catch (Exception e) {
        Log.d("tag", "" + e);
    }

In the above test, some of them failed. I dont know the reason as it need further investigation. But this will get you started.

Secondly, also look for this api from theme, if you want to pick the right png using the rules that android platform uses for find the suitable resource based on the orientation, locale etc.

havexz
  • 9,550
  • 2
  • 33
  • 29
0

How about putting them in a same directory, then automatically querying the directory content and have it create an array using the contents?

Mateusz Kowalczyk
  • 2,036
  • 1
  • 15
  • 29