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

3.2k Views Asked by At

I have this attribute declared on attrs.xml:

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

I need to get its 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?

2

There are 2 best solutions below

3
On BEST ANSWER

No, this is not the correct way, as the integer R.attr.customColorFontContent is a resource identifier generated by Android Studio when your app is compiled.

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 {
            a.recycle();
        }
    }
}

You can then use it like this:

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

You should access color attribute as follows:

public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
    try {
        color = ta.getColor(R.styleable.MyCustomView_customColorPrimary, android.R.color.white); //WHITE IS THE DEFAULT COLOR
    } finally {
        ta.recycle();
    }

    ...
}