是否有可能以编程方式接收由a [int]保存的资源-id而不引用资源类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>
问题是我无法解析定义的'declare-styleable'属性的ID - 始终返回0x00:
int id = context.getResources().getIdentifier( "com_facebook_login_view", "declare-styleable", context.getPackageName() );
int[] resourceIDs = context.getResources().getIntArray( id );
答案 0 :(得分:15)
以下解决方案以编程方式为child-<attr>-tags
标记定义的<declare-styleable>
提供资源ID:
/*********************************************************************************
* 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;
}
也许这有一天可以帮助某人。
答案 1 :(得分:1)
稍微有效的解决方案:
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;
}
答案 2 :(得分:0)
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;
}