NullPointerException
NullPointerException

Reputation: 37733

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?

Upvotes: 1

Views: 3394

Answers (2)

TR4Android
TR4Android

Reputation: 3246

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

Upvotes: 4

Ugurcan Yildirim
Ugurcan Yildirim

Reputation: 6142

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();
    }

    ...
}

Upvotes: 0

Related Questions