• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Generate Dynamic Resource Array From R.java Howto

danjartin

Lurker
Hello all,

I have many images in my drawable-mdpi resource folder that R.java class file loads up dynamically. In my application code I would like to reference all of these images that defined in the R.java file.

public final class R {
public static final class attr {
}
public static final class drawable {
public static final int arrowinverse=0x7f020000;
public static final int bm1=0x7f020001;
public static final int bm10=0x7f020002;
public static final int bm11=0x7f020003;
public static final int bm12=0x7f020004;
public static final int bm2=0x7f020005;
public static final int bm3=0x7f020006;
public static final int bm4=0x7f020007;
public static final int bm5=0x7f020008;
public static final int bm6=0x7f020009;
public static final int bm7=0x7f02000a;
public static final int bm8=0x7f02000b;
public static final int bm9=0x7f02000c;


I was hoping there was a way I could put these file labels inside an array in my code dynamically instead of having to do something like this

test[0] = R.drawable.bm7;
test[1] = R.drawable.bm7;
test[2] = R.drawable.bm7;

for each image when I have over 200 images. I hope I have explained my problem clear enough. My last idea was to create a dynamic string and convert that to an int and put it inside an array which did not work.


for(int count = 1; count <13; count++){


String num = Integer.toString(count);

imagContainer[count] = Integer.parseInt("R.drawable." + "bm" + "num");


}

Any ideas?

Thanks,

Dan
 
Hi,

Here is the code I used:

Resources resource;
DisplayMetrics metrics = new DisplayMetrics();
int id;

getWindowManager().getDefaultDisplay().getMetrics(metrics);
resource = new Resources(getAssets(), metrics, null);

id = resource.getIdentifier("bm" + num, "drawable", "com.android.my_app");

If id is 0 then the ressource does not exist. You have to change the first and the third argument of the getIdentifier function.

Vincent
 
Back
Top Bottom