我希望通过代码获取一个属性的指向引用。在我的xml布局中,我可以像这样轻松地获取引用的drawable:
android:background="?attr/listItemBackground"
属性引用是由我的主题设置的。我想知道是否可能通过代码获取该引用的可绘制对象。
我可以通过创建样式属性并在自定义视图中读取该值来解决这个问题,但在这种情况下,我想弄清楚是否可以在不进行所有这些操作的情况下实现此目标。我认为这应该是可能的,但是我还没有找到获取该属性引用的方法。
谢谢!
我希望通过代码获取一个属性的指向引用。在我的xml布局中,我可以像这样轻松地获取引用的drawable:
android:background="?attr/listItemBackground"
属性引用是由我的主题设置的。我想知道是否可能通过代码获取该引用的可绘制对象。
我可以通过创建样式属性并在自定义视图中读取该值来解决这个问题,但在这种情况下,我想弄清楚是否可以在不进行所有这些操作的情况下实现此目标。我认为这应该是可能的,但是我还没有找到获取该属性引用的方法。
谢谢!
这是正确的操作方式:
// 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();
你不应该使用:
android:background="@drawable/listItemBackground"
然后:
myImageButton.getBackgroundDrawable()
或许我没有理解...
getIndex(0)
返回的)。 - Antoine Marques