Access resource defined in theme and attrs.xml android

Another possible way to do it:

public static int getResIdFromAttribute(final Activity activity,final int attr) {
    if(attr==0)
        return 0;
    final TypedValue typedvalueattr=new TypedValue();
    activity.getTheme().resolveAttribute(attr,typedvalueattr,true);
    return typedvalueattr.resourceId;
}

Or in Kotlin:

@JvmStatic
fun getResIdFromAttribute(activity: Activity, attr: Int): Int {
    if (attr == 0)
        return 0
    val typedValue = TypedValue()
    activity.theme.resolveAttribute(attr, typedValue, true)
    return typedValue.resourceId
}

no need to recycle anything here...

usage:

int drawableResId=getResIdFromAttribute(this,R.attr.homeIcon);
Drawable drawable = getResources().getDrawable(drawableResId);

I think you can get the Drawable with this code:

TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});     
int attributeResourceId = a.getResourceId(0, 0);
Drawable drawable = getResources().getDrawable(attributeResourceId);
a.recycle();