Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve drawable from attributes reference

I defined theme and style inside my app. icons (drawable) are defined using reference in style file as

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

and style as

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

I need to retrieve the drawable programmatically to use the good image in a dialogfragment. If I make like

mydialog.setIcon(R.style.myicon);

I get an id equals to 0, so no image

I tried to use something like

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

I tried different things like that but result is always 0 or null :-/

How I can I do this ?

like image 649
arnouf Avatar asked Mar 11 '13 13:03

arnouf


2 Answers

I found the solution on 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);
like image 145
arnouf Avatar answered Oct 06 '22 18:10

arnouf


Kotlin solution:

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")
like image 42
Sevastyan Savanyuk Avatar answered Oct 06 '22 17:10

Sevastyan Savanyuk