androidattrandroid-attributesattrs.xml

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


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?


Solution

  • 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);