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 ?
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);
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With