Reputation: 3021
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!
Upvotes: 1
Views: 286
Reputation: 10938
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]);
}
Upvotes: 0
Reputation: 128428
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());
*/
}
Upvotes: 3
Reputation:
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);
}
Upvotes: 2
Reputation: 32949
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.
Upvotes: 0