I would like to display all resource drawables in a list so that the user can select one. Is there any way to loop through all R.drawable items so I don't have to hard code them into my program?
Asked
Active
Viewed 1.4k times
2 Answers
32
Using the getFields method on the drawable class, you are able to iterate through the entire list of drawables.
Field[] drawables = android.R.drawable.class.getFields();
for (Field f : drawables) {
try {
System.out.println("R.drawable." + f.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
Reference: http://www.darshancomputing.com/android/1.5-drawables.html

Seidr
- 4,946
- 3
- 27
- 39
-
6using `android.R` will give only the native drawables in the Android SDK. In order to get your app's drawables, use `com.example.appname.R` – Anonsage Jul 06 '13 at 00:21
-
Why are you catching a generic exception? – S-K' Jul 09 '13 at 02:31
-
I'm not sure - it has been quite a while since I wrote this answer. There must of been a reason.. – Seidr Jul 09 '13 at 09:36
-
awesome! i needed a list of font resources and `R.font.class.getFields()` worked great. – ccpizza Feb 09 '19 at 13:48
0
If you look inside your generated R.drawable object you will see that the IDs are contiguous, in my case (and probably yours) beginning at 0x7f020000. As they seem to be sorted by alpha you could probably add dummy images AAAAAAA.png and ZZZZZZ.png and iterate between the two IDs exclusively.
I can't endorse your reasons for attempting this, but I reckon that would work.

Jim Blackler
- 22,946
- 12
- 85
- 101
-
You are right. See my answer here: http://stackoverflow.com/a/19131585/1287856 It also works to iterate in the raw/ folder as well as the xml/ folder. – Mikaël Mayer Oct 03 '13 at 09:11