Retrieving all Drawable resources from Resources object Retrieving all Drawable resources from Resources object android android

Retrieving all Drawable resources from Resources object


Okay, this feels a bit hack-ish, but this is what I came up with via Reflection. (Note that resources is an instance of class android.content.res.Resources.)

final R.drawable drawableResources = new R.drawable();final Class<R.drawable> c = R.drawable.class;final Field[] fields = c.getDeclaredFields();for (int i = 0, max = fields.length; i < max; i++) {    final int resourceId;    try {        resourceId = fields[i].getInt(drawableResources);    } catch (Exception e) {        continue;    }    /* make use of resourceId for accessing Drawables here */}

If anyone has a better solution that makes better use of Android calls I might not be aware of, I'd definitely like to see them!


i used getResources().getIdentifier to scan through sequentially named images in my resource folders. to be on a safe side, I decided to cache image ids when activity is created first time:

    private void getImagesIdentifiers() {    int resID=0;            int imgnum=1;    images = new ArrayList<Integer>();    do {                    resID=getResources().getIdentifier("img_"+imgnum, "drawable", "InsertappPackageNameHere");        if (resID!=0)            images.add(resID);        imgnum++;    }    while (resID!=0);    imageMaxNumber=images.size();}


I have taken Matt Huggins great answer and refactored it to make it more generic:

public static void loadDrawables(Class<?> clz){    final Field[] fields = clz.getDeclaredFields();    for (Field field : fields) {        final int drawableId;        try {            drawableId = field.getInt(clz);        } catch (Exception e) {            continue;        }        /* make use of drawableId for accessing Drawables here */    }   }

Usage:

loadDrawables(R.drawable.class);