Как получить ссылку attr в коде? - программирование

Как получить ссылку attr в коде?

Я ищу, чтобы получить ссылку с атрибута через код. В моих xml-макетах я могу легко получить ссылочный чертеж следующим образом:

android:background="?attr/listItemBackground"

Ссылка на атрибут устанавливается моей темой. Я смотрю, можно ли получить этот ссылочный код с помощью кода.

Я могу обойти это, создав стиль attr и прочитав значение внутри пользовательского представления, но в этом случае я хочу выяснить, возможно ли это, не делая все это. Я бы подумал, что это будет возможно, но я не нашел способы получить эту ссылку атрибута.

Спасибо!

4b9b3361

Ответ 1

Вот как вы это делаете:

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

Ответ 2

Не следует использовать:

android:background="@drawable/listItemBackground"

И затем:

myImageButton.getBackgroundDrawable()

Или, может быть, я не понял...