Skip to content Skip to sidebar Skip to footer

Dynamically Getting All Image Resource Id In An Array

there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array. currently

Solution 1:

you can Use Reflection to achieve this.

import the Field class

import java.lang.reflect.Field;

and then write this in your code

Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = newint[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
    try {
        resArray[i] = ID_Fields[i].getInt(null);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

resArray[] now holds references to all the drawables in your application.

Solution 2:

Well, If your image names are img1, img2 and so on, then you can create a variable like

Stringurl="drawable/"+"img"+i;

intimageKey= getResources().getIdentifier(url, "drawable", getPackageName());

you can also replace your getPackageName() method by your package name like "com.android.resource" Simply,the general function is

publicint getIdentifier(String name, String defType, String defPackage)

Post a Comment for "Dynamically Getting All Image Resource Id In An Array"