5

I have a long series of graphics -- icon1_0.png, icon1_1.png, icon1_2.png..., icon12_0.png, icon12_1.png, icon12_2.png -- and I'd like to package them with my android application. Ideally I think I should be able to load them as resources but the resource id's are set up as java identifiers. Of course, java identifiers can't be assembled at runtime. I have to ask for R.drawable.icon12_00 so I cannot set up a loop

for(int icon=0;icon<12;icon++)
 for(int frame=0;frame<3;frame++)
  //syntax error obviously
  BitmapFactory.decodeResource(getResources(), R.drawable."icon" + icon + "_" + frame + ".png");

So is there any way to get resources by their names? Better yet, is there a canonical way outside the resource system to pack data files into an android application package so that I can get at them?

I'm thinking about reflection but that doesn't seem like the right solution to me.

Brian
  • 8,454
  • 5
  • 27
  • 30

3 Answers3

13

Use getResources().getIdentifier() from your Context (e.g., Activity), but please cache the result if you will use it more than once. getIdentifier() is implemented on Resources.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
6

I know you've found an answer already, but if you use reflection then you will see a good speed increase, as getIdentifier() is slower. I wrote about how to do the reflection method here. However, this only works if you're accessing your own resources.

Dan Lew
  • 85,990
  • 32
  • 182
  • 176
  • How about that. This is a little faster. It's a shame, though, because reflection is notoriously pokey so getIdentifier must be monster slow. – Brian Jan 26 '10 at 02:56
2

Reflection is also very slow, you should just create an array with all of your identifies in it.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • 2
    Do you mean, just write the whole loop out in code? Or something more clever? I'd be interested in the latter, because it would be a nice speed boost if I could get a resource even faster than using reflection (but this would be in a slightly different circumstance, where app data refers to resources - not in code). – Dan Lew Jan 25 '10 at 17:08
  • @DanielLew he is saying you have a code generator which writes the whole loop out in code for you – Pacerier Feb 17 '12 at 00:59