Android: Programmatically iterate through Resource ids

前端 未结 3 472
终归单人心
终归单人心 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;
        }
    }
    

提交回复
热议问题