Get the resource id for the drawable reference used in styled attribute

ilomambo picture ilomambo · May 4, 2013 · Viewed 18.6k times · Source

Having this custom view MyView I define some custom attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="normalColor" format="color"/>
        <attr name="backgroundBase" format="integer"/>
    </declare-styleable>   
</resources>

And assign them as follows in the layout XML:

    <com.example.test.MyView
        android:id="@+id/view1"
        android:text="@string/app_name"
        . . .
        app:backgroundBase="@drawable/logo1"
        app:normalColor="@color/blue"/>

At first I thought I can retrieve the custom attribute backgroundBase using:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank);

Which works only when the attribute is not assigned and the default R.drawable.blank is returned.
When app:backgroundBase is assigned an exception is thrown "Cannot convert to integer type=0xn" because, even though the custom attribute format declares it as integer, it really references a Drawable and should be retrieved as follows:

Drawable base = a.getDrawable(R.styleable.MyView_backgroundBase);
if( base == null ) base = BitMapFactory.decodeResource(getResources(), R.drawable.blank);

And this works.
Now my question:
I really don't want to get the Drawable from the TypedArray, I want the integer id corresponding to app:backgroundBase (in the example above it would be R.drawable.logo1). How can I get it?

Answer

ilomambo picture ilomambo · May 4, 2013

It turns out that the answer was right there:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
int base = a.getResourceId(R.styleable.MyView_backgroundBase, R.drawable.blank);