2013-03-11 67 views
7

我在我的应用程序中定义了主题和样式。图标(绘制)使用的样式文件中引用作为如何从属性检索drawable参考

<attr name="myicon" format="reference" /> 

和风格

<style name="CustomTheme" parent="android:Theme.Holo"> 
    <item name="myicon">@drawable/ajout_produit_light</item> 

我需要以编程方式检索绘制在dialogfragment使用的良好形象定义。 如果我做出这样

mydialog.setIcon(R.style.myicon); 

我得到一个ID等于0,所以没有像

我试图用类似

int[] attrs = new int[] { R.drawable.myicon}; 
TypedArray ta = getActivity().getApplication().getTheme().obtainStyledAttributes(attrs); 
Drawable mydrawable = ta.getDrawable(0); 
mTxtTitre.setCompoundDrawables(mydrawable, null, null, null); 

我想这样的不同的东西,但结果总是0或空的: -/

我如何我能做到这一点?

回答

11

我发现 Access resource defined in theme and attrs.xml android

TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});  
int attributeResourceId = a.getResourceId(0, 0); 
Drawable drawable = getResources().getDrawable(attributeResourceId); 
+5

不要忘记a.recycle – 2016-03-15 17:07:27

+0

呼吁任何其他人在想:'a.recycle()'将信号,即分配的内存不再使用和'了'相关的数据可以返回到内存池立即而不是等待垃圾收集。作为回答[这里](http://stackoverflow.com/questions/7252839/what-is-the-use-of-recycle-method-in-typedarray) – Prof 2017-03-04 23:44:15

0

,仿佛你正试图设置使用资源的myDialog的图标,这似乎解决方案,并试图通过R.style但你的其他代码来访问它段引导我相信你有资源位于R.drawable

考虑到这一点,你应该能够得到你想要的效果与myDialog.setIcon(R.drawable.myicon);