0

I have these images in the drawable folder:

image_1.png
image_2.png
image_3.png
...
image_n.png

And I have a PlayerDTO that has an id attribute like this:

public class PlayerDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private int id;

    //... getters and setters

}

I need to establish a match between the player id and it corresponding image to set it in an ImageView. e.g.:

player id = 1. It's image is image_1.png
player id = 2. It's image is image_2.png
...
player id = n. It's image is image_n.png

This is the same but this is not dynamically:

ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(R.drawable.image_1);

How can I do this programmatically and dynamically?

John Alexander Betts
  • 4,718
  • 8
  • 47
  • 72
  • 1
    If I have interpreted your question correctly you have string with the name of your drawable, and you need to find the corresponding ID. Have a look at this [link](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string). Does that clear up the issue? – Lasse Samson Nov 17 '13 at 22:14

1 Answers1

1

If you mean you're trying to get the names of your resources programmatically then something like this:

int[] drawableId = new int[totalNumberOfImages];
String drawableName;
for (int n = 1; n < totalNumberOfImages; n++) {
    drawableName = "image_" + n;
    drawableId[n] = getResources().getIdentifier(drawableName, "drawable", getPackageName());
}

That will give you an array of ID's for the drawables.

To get a direct correlation instead, you could use a SparseIntArray something like:

int drawableId;
String drawableName;
SparseIntArray playerImages = new SparseIntArray(totalNumberOfPlayers);
for (int n = 1; n < totalNumberOfPlayers; n++) {
    drawableName = "image_" + n;
    drawableId = getResources().getIdentifier(drawableName, "drawable", getPackageName());
    playerImages.put(n, drawableId);
}
Sound Conception
  • 5,263
  • 5
  • 30
  • 47