2012-12-11 18 views
6

我有一个问题,我找不到任何帮助:访问<申报,设置样式>资源编程

是否有可能,接收被保留资源的IDS由一个int []无需编程引用资源类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> 

的问题是,我无法解析定义的“申报,设置样式”属性的ID - 0×00总是返回:

int id = context.getResources().getIdentifier("com_facebook_login_view", "declare-styleable", context.getPackageName()); 
int[] resourceIDs = context.getResources().getIntArray(id); 

任何想法将不胜感激! :)

在此先感谢!

克里斯托弗

+2

这是因为它是一个声明,设置样式,而不是一个标识符。你有没有尝试对R.styleable课程进行思考? – njzk2

+0

不,我没有提到这一点 - 感谢提示 - 我会尝试使用反射:) 所以没有办法动态访问声明样式? 我会用它的方法 getContext()。obtainStyledAttributes(AttributeSet set,int [] attrs); 感谢您的帮助! –

+2

解决了它。但我的声望太低,回答我自己的问题:( 如果它不会被遗忘,我会在八小时内发布它;) –

回答

15

下面是编程提供的资源的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; 
} 

也许这可以帮助别人一天。 :)

问候

克里斯托弗

+0

并再次感谢njzk2的绊脚石:) –

+1

很好的答案..谢谢 – Arunkumar

+1

它必须是被接受的答案,因为它提供了100%的R.styleable独立解决方案。 –

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; 
    } 
相关问题