如何从属性引用中检索drawable

arn*_*ouf 11 user-interface android

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

<attr name="myicon" format="reference" />
Run Code Online (Sandbox Code Playgroud)

和风格一样

<style name="CustomTheme" parent="android:Theme.Holo">
    <item name="myicon">@drawable/ajout_produit_light</item>
Run Code Online (Sandbox Code Playgroud)

我需要以编程方式检索drawable以在dialogfragment中使用良好的图像.如果我做的话

mydialog.setIcon(R.style.myicon);
Run Code Online (Sandbox Code Playgroud)

我得到一个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);
Run Code Online (Sandbox Code Playgroud)

我试过不同的东西,但结果总是0或null: - /

我怎么能这样做?

arn*_*ouf 18

我找到了在theme和attrs.xml android中定义的Access资源的解决方案

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

  • 别忘了给a.recycle打电话 (8认同)
  • 对于任何其他想知道的人:a.recycle()将发出信号,表明已分配的内存已不再使用,并且与a关联的数据可以立即返回到内存池,而不必等待垃圾回收。如回答[这里](http://stackoverflow.com/questions/7252839/what-is-the-use-of-recycle-method-in-typedarray) (3认同)

Sev*_*yuk 5

Kotlin解决方案:

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

  • @PeterKeefe `.apply` 使代码可读性较差,应谨慎使用。Kotlin 不在于简洁,而在于可读性。 (2认同)