Android - Using reference attributes in source code

   Android's style property is often used to either directly refer to a specific style or a theme specific style via reference attributes. This works fine in a layout, however in some cases the Java source code of a custom view might need to do the same. In such cases, trying to directly use the reference attribute via R.attr isn't going to work as that is just going to give the id of the attribute and not that of the resource being referred to. In C style, it would be like a ptr instead of *ptr. The dereference can be performed via the current theme.

    TypedValue resolvedValue = new TypedValue();
    context.getTheme().resolveAttributes(R.attr.referenceAttributeName, resolvedValue, true);
    int actualResourceId = resolvedValue.resourceId;


    actualResourceId could now be used for any APIs which expects the resource id like setImageResource() etc.

No comments: