Andreas
Andreas

Reputation: 2313

refer to an image with an array content

how is it possible to refer to an image with an array index at the end of the image name? Here is the code i would like to work (doesnt though...:()

for (int i = 0; i < melodiToner.length; i++)

setImageResource(R.drawable.gronpil+melodiToner[i]);

i.e I would like to load image gronpil1.png in the first loop, gronpil2.png in the second. This isnt relative to the array content, I need some other file name endings so i cannot use the i variable, it has to be from the array.

Thanks for all help!

Andreas

Upvotes: 0

Views: 57

Answers (2)

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

This way (short version):

for (int i = 0; i < melodiToner.length; i++) {
    int resId = getResources().getIdentifier("gronpil"+melodiToner[i], "drawable", getPackageName());
    setImageResource(resId);
}

Longer version as to not call getResources and getPackageName once in every loop:

Resources resources = getResources();
String packageName = getPackageName();
for (int i = 0; i < melodiToner.length; i++) {
    int resId = resources.getIdentifier("gronpil"+melodiToner[i], "drawable", packageName);
    setImageResource(resId);
}

Upvotes: 1

MAC
MAC

Reputation: 15847

create array of integer

int[] img = new int[5];

img[0] = R.drawable.no1;
img[1] = R.drawable.no2;
img[2] = R.drawable.no3;
img[3] = R.drawable.no4;
img[4] = R.drawable.no5;

(int i = 0; i < 5; i++){
    imgView.setImageResource(img[i]);
}

Upvotes: 0

Related Questions