Acceso a recursos <declare-styleable> por programación
Tengo una pregunta en la que no pude encontrar ninguna ayuda:
¿Es posible recibir los resource-ids que están siendo guardados por a como un int [] programatically sin referirse a la clase de recurso R?
<declare-styleable name="com_facebook_login_view"> <attr name="confirm_logout" format="boolean"/> <attr name="fetch_user_info" format="boolean"/> <attr name="login_text" format="string"/> <attr name="logout_text" format="string"/> </declare-styleable>
El problema es que no puedo resolver el ID del atributo 'declare-styleable' definido – 0x00 siempre se devuelve:
int id = context.getResources().getIdentifier( "com_facebook_login_view", "declare-styleable", context.getPackageName() ); int[] resourceIDs = context.getResources().getIntArray( id );
Cualquier idea sería muy apreciada! 🙂
¡Gracias por adelantado!
Christopher
Solución ligeramente más eficiente:
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; }
Esta es la solución que entrega los ID de recursos de forma programática para las etiquetas secundarias definidas para una etiqueta:
/********************************************************************************* * 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; }
Tal vez esto podría ayudar a alguien algún día. 🙂
Saludos
Christopher