1

Similar question to Android: Set a random image using setImageResource, but I think I'm looking for a different answer.

As mentioned in the linked post, this:

int p = R.drawable.photo;
image.setImageResource(p);

displays photo1, but something like this:

String a = "R.drawable.";
String b = "photo";
String c = a+b;
int p = Integer.parseInt(c);
image.setImageResource(p);

will not. I have a lot of images, and an array contining all of the image names, so I want to fill an array something like:

int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = ("R.drawable." + image_names[i]);

but I get a runtime error. Is there any way to make this loop work? Or better ways to cue up image ID's into an array?

Thanks!

Community
  • 1
  • 1
Lableable
  • 89
  • 1
  • 10

1 Answers1

1

You can use this method and it will retrun the source id based off a string. The second and third paramaters are optional but if you can put them in I would.

public int getIdentifier (String name, String defType, String defPackage) 

Example:

int p = getIdentifier("photo","drawable")

Or if you are getting ids all the time you could create a function like:

public int getDrawableId(Context context, String name){
    return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}

You just have to check to see if it returns 0 because that means it did not find it.

EDIT

For your example up there just impliment the function above and change it to this:

int imageArray[] = new int[number_of_images];
for (int i = 0; i < numImages; i++)
imageArray[i] = getDrawableId(getApplicationContext(),"R.drawable." + image_names[i]);
ObieMD5
  • 2,684
  • 1
  • 16
  • 26