[TinyTut] - Getting all DrawableIDs (or StringIDs, ...)
What you learn: You will learn how to get all Resources of the resource-classes within the R.java (like all DrawableIDs or all StringIDs). This Tutorial uses the Java Reflection API (no need for you to code on your own
).Difficulty: 1.5 of 5

Description: Up to now there is no function within the Android SDK to retrieve all IDs of a resource-classes of the R.java. So I coded one for you:
Example-Call:
Using java Syntax Highlighting
- int[] allDrawableIDs = getAllResourceIDs(R.drawable.class);
- // or...
- int[] allStringIDs = getAllResourceIDs(R.string.class);
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
The Source:
Using java Syntax Highlighting
- // Necessary Imports:
- import java.lang.reflect.Field;
- // End of imports
- /**
- * Retrieve all IDs of the Resource-Classes
- * (like <code>R.drawable.class</code>) you pass to this function.
- * @param aClass : Class from R.XXX, like: <br>
- * <ul>
- * <li><code>R.drawable.class</code></li>
- * <li><code>R.string.class</code></li>
- * <li><code>R.array.class</code></li>
- * <li>and the rest...</li>
- * </ul>
- * @return array of all IDs of the R.xyz.class passed to this function.
- * @throws IllegalArgumentException on bad class passed.
- * <br><br>
- * <b>Example-Call:</b><br>
- * <code>int[] allDrawableIDs = getAllResourceIDs(R.drawable.class);</code><br>
- * or<br>
- * <code>int[] allStringIDs = getAllResourceIDs(R.string.class);</code>
- */
- private int[] getAllResourceIDs(Class<?> aClass) throws IllegalArgumentException{
- /* Get all Fields from the class passed. */
- Field[] IDFields = aClass.getFields();
- /* int-Array capable of storing all ids. */
- int[] IDs = new int[IDFields.length];
- try {
- /* Loop through all Fields and store id to array. */
- for(int i = 0; i < IDFields.length; i++){
- /* All fields within the subclasses of R
- * are Integers, so we need no type-check here. */
- // pass 'null' because class is static
- IDs[i] = IDFields[i].getInt(null);
- }
- } catch (Exception e) {
- /* Exception will only occur on bad class submitted. */
- throw new IllegalArgumentException();
- }
- return IDs;
- }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
Regards,
plusminus



