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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With