SourabhTech
SourabhTech

Reputation: 1377

How to set images id dynamically in integer array

Here is my code, I have 100 images and i want to create it dynamic using loop but it's not working.

   int[] imgIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3};

Upvotes: 0

Views: 773

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Try using getResources().getIdentifier to create array of drawable id's if drawables name is as img1,img2,img3,..

int[] imgIds = new int [100];
int imagecount=1;
for(int i=0;i<100;i++){
imgIds[i]=getResources().getIdentifier("img"+imagecount,
                                           "drawable", getPackageName());
imagecount++;
}

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157457

if your images are all called with the same prefix and the only thing it does change is the number you can do the following thing:

Suppose you numbered from 0 to size -1

ArrayList<Integer> imgIds = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
  imgIds.add(getResources().getIdentifier("img"+i, "drawable", getPackageName());
}

check for typo. Edit. With array:

int[] imgIds = new int[size];
for (int i = 0; i < size; i++) {
  imgIds[i] = getResources().getIdentifier("img"+i, "drawable", getPackageName();
}

Upvotes: 1

Related Questions