Skip to content Skip to sidebar Skip to footer

Android: Programmatically Iterate Through Resource Ids

I want to be able to iterate through all of the fields in the generated R file. Something like: for(int id : R.id.getAllFields()){ //Do something with id, like create a view for ea

Solution 1:

I found that "Class.forName(getPackageName()+".R$string");" can give you access to the string resources and should work for id, drawable, exc as well.

I then use the class found like this:


import java.lang.reflect.Field;

import android.util.Log;

publicclassResourceUtil {

    /**
     * Finds the resource ID for the current application's resources.
     * @param Rclass Resource class to find resource in. 
     * Example: R.string.class, R.layout.class, R.drawable.class
     * @param name Name of the resource to search for.
     * @return The id of the resource or -1 if not found.
     */publicstaticintgetResourceByName(Class<?> Rclass, String name) {
        intid= -1;
        try {
            if (Rclass != null) {
                finalFieldfield= Rclass.getField(name);
                if (field != null)
                    id = field.getInt(null);
            }
        } catch (final Exception e) {
            Log.e("GET_RESOURCE_BY_NAME: ", e.toString());
            e.printStackTrace();
        }
        return id;
    }
}

Solution 2:

Your reply to my comment helped me get a better idea of what you're trying to do.

You can probably use ViewGroup#getChildAt and ViewGroup#getChildCount to loop through various ViewGroups in your view hierarchy and perform instanceof checks on the returned Views. Then you can do whatever you want depending on the type of the child views and where they are in your hierarchy.

Solution 3:

You can use reflection on an inner class, but the syntax is packagename.R$id. Note that reflection can be very slow and you should REALLY avoid using it.

Post a Comment for "Android: Programmatically Iterate Through Resource Ids"