Android: Programmatically iterate through Resource ids

前端 未结 3 458
终归单人心
终归单人心 2020-12-15 11:30

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 wit         


        
相关标签:
3条回答
  • 2020-12-15 11:56

    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;
    
    public class ResourceUtil {
    
        /**
         * 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.
         */
        public static int getResourceByName(Class<?> Rclass, String name) {
            int id = -1;
            try {
                if (Rclass != null) {
                    final Field field = 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 12:03

    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.

    0 讨论(0)
  • 2020-12-15 12:12

    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.

    0 讨论(0)
提交回复
热议问题