如何得到code中的ATTR参考?code、ATTR

2023-09-03 22:56:42 作者:忘不掉的是你和他的暧昧▓

我期待获得通过code属性指向的参考。在我的XML的布局,我可以很容易地被引用的绘制是这样的:

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"

属性值是由我的主题设置。我想看看是否有可能获得通过code表示引用的绘制。

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

我可以解决此通过创建风格ATTR和读取里面的自定义视图,但在这种情况下,我想弄清楚,如果这是可能的,而不做所有的值。我认为这是可能的,但我还没有找到方法来获得该属性的参考。

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.

谢谢!

推荐答案

这是你如何做到这一点:

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