Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count items in drawable folder that start with specific string

How would I count the number of items in the drawable folder that start with "fr"?

Background; I want to create a randomizer to pick a random image from the drawables folder. To make it future-proof, I want to set the max value of the randomizer to the number of items that are eligable for picking..

like image 542
Kees Koenen Avatar asked Feb 22 '12 20:02

Kees Koenen


1 Answers

Like other resources in Android, drawables are accessed through 'R' class, which is just collection of static classes containing static integer fields. There is no "get all drawable names" metthod (at least I don't know it) apart from using reflection.

You would need a list of drawable ids to randomize from. You can automatically fill this list using reflection:

    import java.lang.reflect.Field;
    ...
    Field[] fields = R.drawable.class.getFields();
    List<Integer> drawables = new ArrayList<Integer>();
    for (Field field : fields) {
        // Take only those with name starting with "fr"
        if (field.getName().startsWith("fr")) {
            drawables.add(field.getInt(null));
        }
    }

This way you get a list of ids of drawables that interest you. You can use those ids later where you would normally use e.g. R.drawable.someResource

like image 154
Tomasz Niedabylski Avatar answered Sep 19 '22 12:09

Tomasz Niedabylski