Matteo Cardellini
Matteo Cardellini

Reputation: 896

Store multi Drawable in an ArrayList with For cycle

I have a lot of images in my project named image_0, image_1, image_2 .... and currently, for storing them in an array, I use

int[] images = {R.drawable.image_0, R.drawable.image_1 ....};

But I have like 400 images and this is very ugly to see in the code so I'd like to use a for cycle like:

ArrayList<Integer> images = new ArrayList<Integer>;
for(int i = 0; i < 400; i++){
   images.add(R.drawable.image_+"i");
}

But they are Int not String.. How can I do that ?

Upvotes: 0

Views: 851

Answers (2)

Yakiv Mospan
Yakiv Mospan

Reputation: 8224

You can deal with it like this :

ArrayList<Integer> images = new ArrayList<Integer>;
for(int i = 0; i < 400; i++){
   images.add(getResId(R.drawable.image_+"i", Drawable.class));
}

//method to convert String ID name into Integer value
public static int getResId(String variableName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

Original anwer is here.

Upvotes: 1

FD_
FD_

Reputation: 12919

This can be done using reflection:

String name = "image_0";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);

Or using Resources.getIdentifier():

String name = "image_0";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

For memory efficiency, I'd still recommend you to store the ids in a String array, and get the images only when you need them.

Upvotes: 0

Related Questions