Android 如何从属性引用中检索drawable

Android 如何从属性引用中检索drawable,android,user-interface,Android,User Interface,我在我的应用程序中定义了主题和风格。图标(可绘制)使用样式文件中的引用定义为 <attr name="myicon" format="reference" /> 我得到的id等于0,所以没有图像 我试着用类似于 int[] attrs = new int[] { R.drawable.myicon}; TypedArray ta = getActivity().getApplication().getTheme().obtainStyledAttributes(attrs); Dr

我在我的应用程序中定义了主题和风格。图标(可绘制)使用样式文件中的引用定义为

<attr name="myicon" format="reference" />
我得到的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或null:-/

我该怎么做

我在上找到了解决方案


似乎您正试图使用资源设置myDialog的图标,并试图通过R.style访问它,但您的其他代码段使我相信您的资源位于R.drawable中

考虑到这一点,您应该能够通过myDialog.setIcon(R.drawable.myicon)获得想要的效果

Kotlin溶液:

val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.yourAttr, typedValue, true)
val imageResId = typedValue.resourceId
val drawable = ContextCompat.getDrawable(context, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId")

不要忘记为任何其他感到疑惑的人调用a.recycle:
a.recycle()
将发出分配的内存不再使用的信号,与
a
关联的数据可以立即返回内存池,而不是等待垃圾回收。正如所回答的那样,如何在
片段中使用它?
单行解决方案:
val drawable=ContextCompat.getDrawable(context,TypedValue().apply{context.theme.resolvattribute(R.attr.myIcon,this,true)}.resourceId)
@peterkefe
。apply
会降低代码的可读性,应谨慎使用。Kotlin不是关于简洁,而是关于可读性。
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);
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});     
int attributeResourceId = a.getResourceId(0, 0);
Drawable drawable = getResources().getDrawable(attributeResourceId);
val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.yourAttr, typedValue, true)
val imageResId = typedValue.resourceId
val drawable = ContextCompat.getDrawable(context, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId")