Obtain styleable fields at runtime

Ususally, when we want to get some “R” attributes at runtime, we use the Resources getIdentifier method, which is useful for getting strings, drawables and ids at runtime. Unfortunately this method cannot be used to get the styleable fields. However, using java reflections, there’s another way to solve the problem. With this snippet you can get styleable fields at runtime in your code:

[cce]public static final <T> T getFieldFromStyleable( Context context, String name ) {
try {
// use reflection to access the resource class
Field field = Class.forName( context.getPackageName() + “.R$styleable” ).getField( name );
if ( null != field ) {
return (T) field.get( null );
}
} catch ( Throwable t ) {
t.printStackTrace();
}
return null;
}[/cce]

Which can be used in this way:
[cce]int[] array = getFieldFromStyleable( context, “MyListView” );
array = context.obtainStyledAttributes( attrs, styleableArray, defStyle, 0 );[/cce]

Share with...