Count the items in the wraparound folder that start on a specific line.

How to count the number of items in a folder with a transfer option starting with "fr"?

Background; I want to create a randomizer to select a random image from the drawables folder. To make this future, I want to set the maximum value of the randomizer to the number of elements that can be obtained for selection.

+6
source share
1 answer

Like other resources in Android, images are accessible through the "R" class, which is just a collection of static classes containing static integer fields. There is no β€œget all available names” metthod (at least I don't know) other than using reflection.

You will need a list of available identifiers for randomization. You can automatically populate this list with 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)); } } 

Thus, you will get a list of identifiers of available objects that interest you. You can use these identifiers later when you usually use, for example. R.drawable.someResource

+10
source

Source: https://habr.com/ru/post/909124/


All Articles