NullPointerException NullPointerException - 5 months ago 15
Android Question

How to get the value of a custom attribute (attrs.xml)?

I have this attribute declared on attrs.xml:

<attr name="customColorPrimary" format="color" value="#076B07"/>

I need to get it's value, which should be "#076B07", but instead I'm getting an integer: "2130771968"

I'm accessing the value this way:

int color = R.attr.customColorFontContent;

Is there a correct way to get the real value of this attribute?

Thank you


No, this is not the correct way, as the integer R.attr.customColorFontContent is a resource identifier.

Instead, you'll need to get the color that is associated with the attribute from the theme. Use the following class to do this:

public class ThemeUtils {
    private static final int[] TEMP_ARRAY = new int[1];

    public static int getThemeAttrColor(Context context, int attr) {
        TEMP_ARRAY[0] = attr;
        TypedArray a = context.obtainStyledAttributes(null, TEMP_ARRAY);
        try {
            return a.getColor(0, 0);
        } finally {

You can then use it like this:

ThemeUtils.getThemeAttrColor(context, R.attr.customColorFontContent);