Accessing resources programmatically

前端 未结 3 537
[愿得一人]
[愿得一人] 2020-12-10 07:36

Is it possible to receive the resource-ids being kept by a as an int[] programmatically without referring to the resource-class R?



        
相关标签:
3条回答
  • 2020-12-10 08:13

    Here is the solution that delivers the resource-IDs programmatically for the child-<attr>-tags defined for a <declare-styleable> tag:

    /*********************************************************************************
    *   Returns the resource-IDs for all attributes specified in the
    *   given <declare-styleable>-resource tag as an int array.
    *
    *   @param  context     The current application context.
    *   @param  name        The name of the <declare-styleable>-resource-tag to pick.
    *   @return             All resource-IDs of the child-attributes for the given
    *                       <declare-styleable>-resource or <code>null</code> if
    *                       this tag could not be found or an error occured.
    *********************************************************************************/
    public static final int[] getResourceDeclareStyleableIntArray( Context context, String name )
    {
        try
        {
            //use reflection to access the resource class
            Field[] fields2 = Class.forName( context.getPackageName() + ".R$styleable" ).getFields();
    
            //browse all fields
            for ( Field f : fields2 )
            {
                //pick matching field
                if ( f.getName().equals( name ) )
                {
                    //return as int array
                    int[] ret = (int[])f.get( null );
                    return ret;
                }
            }
        }
        catch ( Throwable t )
        {
        }
    
        return null;
    }
    

    Maybe this could help somebody one day.

    0 讨论(0)
  • 2020-12-10 08:13
    public static final int[] getResourceDeclareStyleableIntArray(String name) {
        int[] result = null;
        try {
            result = (int[]) R.styleable.class.getField(name).get(R.styleable.class);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-10 08:24

    Slightly more efficient solution:

    public static final int[] getResourceDeclareStyleableIntArray(String name) {
            Field[] allFields = R.styleable.class.getFields();
            for (Field field : allFields) {
                if (name.equals(field.getName())) {
                    try {
                        return (int[]) field.get(R.styleable.class);
                    } catch (IllegalAccessException ignore) {}
                }
            }
    
            return null;
        }
    
    0 讨论(0)
提交回复
热议问题