How to get the attr reference in code?

I'm looking to get the pointing reference from an attribute via code. In my xml layouts I can easily get the referenced drawable like this:

android:background="?attr/listItemBackground"

The attribute reference is set by my Theme. I'm looking to see if it's possible to get that referenced drawable via code.

I can work around this by creating style attr and reading the value inside a custom view but in this case I want to figure out if this is possible without doing all that. I would think it would be possible but I haven't found ways to get that attribute reference.

Thanks!


This is how you do it:

// Create an array of the attributes we want to resolve
// using values from a theme
int[] attrs = new int[] { R.attr.listItemBackground /* index 0 */};

// Obtain the styled attributes. 'themedContext' is a context with a
// theme, typically the current Activity (i.e. 'this')
TypedArray ta = themedContext.obtainStyledAttributes(attrs);

// To get the value of the 'listItemBackground' attribute that was
// set in the theme used in 'themedContext'. The parameter is the index
// of the attribute in the 'attrs' array. The returned Drawable
// is what you are after
Drawable drawableFromTheme = ta.getDrawable(0 /* index */);

// Finally, free the resources used by TypedArray
ta.recycle();