1

Basically I'm trying to automate process of

mDrawable[0] = this.getResources().getDrawable(R.drawable.img0);
mDrawable[1] = this.getResources().getDrawable(R.drawable.img1);
mDrawable[2] = this.getResources().getDrawable(R.drawable.img2);
mDrawable[3] = this.getResources().getDrawable(R.drawable.img3);
mDrawable[4] = this.getResources().getDrawable(R.drawable.img4);

etc..

to a loop:

for(int i = 0;i<=15;i++)
{       
mDrawable[i] = this.getResources().getDrawable(R.drawable.**img+i**);       
}

So how do I make up this resource name img4 from i loop variable

Thanks!

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
Sergej Popov
  • 2,933
  • 6
  • 36
  • 53

4 Answers4

3

I am sure you want to implement this kind of example.

This is helpful when you want to implement findViewById() inside a loop when there are many number of views with just a difference like "counter" varialbe 1, 2,3,4,5,etc.

for(int i=0; i<15; i++) 
{
    String imageID = "img" + (i);
    int resID = getResources().getIdentifier(imageID, "drawable", getPackageName());

  /* if you want to reference any widgets like Button, TextView, ImageView, etc. then write below code:

    //int resID = getResources().getIdentifier(imageID, "id", getPackageName());   
  */
}
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • `"id"` is not valid here since those are drawable ids, use `"drawable"` instead. Otherwise you'll end with 0, which is a invalid reference. –  Nov 15 '11 at 11:51
  • `getPackageName()` is a `Context` method, so if you are not in a class that extends context (e.g. a activity or a service) you have to get hold of a context instance and use `ctx.getPackageName()`. Alternatively use a String literal `"com.your.packagename"` instead. –  Nov 15 '11 at 12:02
  • @alextsc thats the exact catch dear. thanx – Paresh Mayani Nov 15 '11 at 12:39
2

You can make use of Resources.getIdentifier()

Small snippet from the top of my head:

for(int i = 0;i<=15;i++)
{   
    int id = this.getResources().getIdentifier("img"+i, "drawable", getPackageName());
    mDrawable[i] = this.getResources().getDrawable(id);       
}
0

Reflection. However, given the overhead of doing the reflection I would suggest with sticking with the above code unless you have a lot more than 4 elements.

Post

Reflection

Community
  • 1
  • 1
John B
  • 32,493
  • 6
  • 77
  • 98
0

To avoid Resource.getIndentifier() (the use of which is discouraged), you could generate an array of ids and iterate through them

int ids[] = { R.drawable.img0, R.drawable.img1, R.drawable.differentnames, R.drawable.whatever /*etc*/ };
mDrawables = new Drawable[ids.length];
for(int i = 0, s = ids.length; i < s; i++)
{       
    mDrawables[i] = this.getResources().getDrawable(ids[i]);       
}
FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37