如何在代码中获取属性引用?

49

我希望通过代码获取一个属性的指向引用。在我的xml布局中,我可以像这样轻松地获取引用的drawable:

android:background="?attr/listItemBackground"

属性引用是由我的主题设置的。我想知道是否可能通过代码获取该引用的可绘制对象。

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

谢谢!

2个回答

114

这是正确的操作方式:

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

1
谢谢你的答案。这似乎是唯一的解决办法。 - Jona
我尝试过使用索引0,但它不起作用,而是使用1(这是由getIndex(0)返回的)。 - Antoine Marques
我不得不将R.attr.listItemBackground替换为R.attr.selectableItemBackground才能编译。 - dimsuz
2
Android的代码非常混乱且不直观。我原以为Google的员工都应该是天才。但实际上,即使是最简单和最明显的事情,也几乎是不可能完成的。 - slashdottir
1
@slashdottir 告诉我关于它的事情。 - KunYu Tsai
如果不起作用,请仔细检查您是否已经附加了onClickListener或将setClickable设置为true,https://dev59.com/TV0Z5IYBdhLWcg3w0jCy#37060165 - BabyishTank

0

你不应该使用:

android:background="@drawable/listItemBackground"

然后:

myImageButton.getBackgroundDrawable()

或许我没有理解...


好的,我的想法是我想从attr/listItemBackground中访问引用的资源,这个资源已经通过theme.xml设置了正确的引用。获取视图中已经设置的背景并不是问题 :) - Jona
好的,我认为可以通过尝试直接从context.getResources()获取"?attr/listItemBackground"来实现。但是我认为还有比引用可绘制对象更好的解决方案。我们可以讨论一下主要思路吗?(如果您认为这个解决方案是最好的,则无需讨论) - Mathieu de Brito
我为我的应用程序设计了一个复杂但有组织的主题。但是,有一个情况我想看看是否可能,并且如何可能使用它。你会认为res.getDrawable(R.attr.listItemBackground)可以做到这一点,因为资源已经正确地设置了当前设置的主题并指向正确的资源。但似乎比那更复杂一些... - Jona
是的,res.getDrawable(R.attr.listItemBackground)就是我想要的... 你正在使用引用,这样当你改变主题时,所有配置都在你的attr资源中。为此,我会创建一个自定义View/Drawable,它从当前Theme中选择值。像这样:android:background="myCustomView"我不记得怎么写了,但是思路已经在这里了。 - Mathieu de Brito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接