访问< declare-styleable>以编程方式资源 [英] Accessing <declare-styleable> resources programmatically

查看:74
本文介绍了访问< declare-styleable>以编程方式资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过编程方式接收a保持为int []的资源ID,而无需引用资源类R?

Is it possible to receive the resource-ids being kept by a as an int[] programmatically without referring to the resource-class 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:

The problem is that I cannot resolve the ID of the defined 'declare-styleable' attribute - 0x00 is always returned:

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

推荐答案

以下是为以<declare-styleable>标签定义的child-<attr>-tags以编程方式提供资源ID的解决方案:

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.

这篇关于访问&lt; declare-styleable&gt;以编程方式资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆