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

问题描述

这就是你的做法:

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

解决方法

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

android:background="?attr/listItemBackground"

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

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

谢谢!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...