如何获得代码中的attr引用?

我期待通过代码从属性获取指向引用。 在我的xml布局中,我可以很容易地得到这样的引用可绘制:

android:background="?attr/listItemBackground" 

属性引用由我的主题设置。 我期待看看是否有可能通过代码获取引用可绘制。

我可以通过创build样式attr和读取自定义视图中的值来解决这个问题,但在这种情况下,我想弄清楚如果没有这样做,这是否可能。 我认为这将是可能的,但我还没有find方法来获得该属性的参考。

谢谢!

这是你如何做到的:

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

你不应该使用:

android:background="@drawable/listItemBackground"

接着:

myImageButton.getBackgroundDrawable()

或者,也许我不明白…