views:

606

answers:

3

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.

+5  A: 

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
Okay, this works. getIdentifier("resname", "restype", "com.domain.appname"); Thank you.
Brian
+4  A: 

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.

Daniel Lew
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
+2  A: 

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

Romain Guy
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).
Daniel Lew