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!

0

4 Answers 4

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());   
  */
}
Sign up to request clarification or add additional context in comments.

3 Comments

"id" is not valid here since those are drawable ids, use "drawable" instead. Otherwise you'll end with 0, which is a invalid reference.
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.
@alextsc thats the exact catch dear. thanx
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);       
}

Comments

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

2 Comments

According to his loop, he has 16 of them
Good catch. I would still code it out rather than using reflection.
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]);       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.