小编典典

如何在代码中获取 attr 引用?

javascript

我希望通过代码从属性中获取指向引用。在我的 xml 布局中,我可以很容易地获得引用的可绘制对象,如下所示:

android:background="?attr/listItemBackground"

属性引用由我的主题设置。我正在寻找是否可以通过代码获取引用的可绘制对象。

我可以通过创建样式 attr 并读取自定义视图中的值来解决这个问题,但在这种情况下,我想弄清楚这是否可能不做所有这些。我认为这是可能的,但我还没有找到获取该属性引用的方法。

谢谢!


阅读 234

收藏
2022-08-03

共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();
2022-08-03