Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

android - Accessing <declare-styleable> resources programmatically

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>

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 );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...