First of all you should probably understand the R class a bit: Read more here
In short: the R
class is a dynamically generated class which contains inner classes (such as the drawable
class). These inner classes contain multiple Integer constants, which are linked to the corresponding resource
This means that, since the drawables here are defined as members of the R.drawable
class we need to use reflection to access them all.
First we need to get hold of an instance of the drawable
subclass. Unfortunately the constructor of this class is private, but we can get around this using a bit more reflection:
Class<R.drawable> drawableClass = R.drawable.class;
R.drawable instance = (R.drawable) drawableClass.getConstructors()[0].newInstance();
Next we create an ArrayList and for each of the Fields which are declared in the R.drawable
class we get the value which are set in our instance (since they are constants those will be the correct values) and add it to the list:
List<Integer> drawables = new ArrayList<>();
for (Field field :
drawableClass.getDeclaredFields()) {
int value = field.getInt(instance);
drawables.add(value);
}
Which already completes all the code needed, you can now use the Integers in the list normally, as if you were using R.drawable.icon
. Note however, that getDeclaredConstructors()
, newInstance()
, getDeclaredFields()
and getInt()
all throw Exceptions, which need to be caught.
Full Snippet (Java):
public static List<Integer> getDrawablesList() throws IllegalAccessException, InvocationTargetException, InstantiationException {
Class<R.drawable> drawableClass = R.drawable.class;
R.drawable instance = (R.drawable) drawableClass.getDeclaredConstructors()[0].newInstance();
List<Integer> drawables = new ArrayList<>();
for (Field field :
drawableClass.getDeclaredFields()) {
int value = field.getInt(instance);
drawables.add(value);
}
return drawables;
}
Full Snippet (Kotlin):
(requires the "org.jetbrains.kotlin:kotlin-reflect:YOUR_KOTLIN_VERSION" dependency)
private fun getDrawablesList() : List<Int> {
val drawableClass = R.drawable::class
val instance = drawableClass.constructors.first().call()
val drawablesList = mutableListOf<Int>()
for (field in instance.javaClass.declaredFields) {
val test = field.getInt(instance)
drawablesList.add(test)
}
return drawablesList
}