Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch getting many bitmap resources on Android

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.

like image 650
Brian Avatar asked Jan 24 '10 22:01

Brian


2 Answers

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.

like image 141
CommonsWare Avatar answered Oct 04 '22 20:10

CommonsWare


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.

like image 21
Dan Lew Avatar answered Oct 04 '22 20:10

Dan Lew