I have a ImageView and I need to programmatically apply the style to this image instead of doing it in xml
<style name="mainicon">
<item name="android:background">@drawable/icon_background</item>
<item name="android:foregroundTint">@drawable/foreground_selector</item>
...
</style>
val buttonImageView = view.findViewById<ImageView>(R.id.main_button) as ImageView
My question is that how I can programmatically apply the style to this image view?
you can't change style of created and attached View
. style may be set in constructor only, so if you are using XML declaration then style is already applied there (by style
attribute, without android:
prefix)
you may remove your current View
and add new in the same place with new style applied by contructor
new ImageView(context, null, R.style.mainicon);
or using ContextThemeWrapper
new ImageView(new ContextThemeWrapper(context, R.style.mainicon));
as an option you may also define in XML two ImageView
s with different styles and switching their Visibility
. this isn't best solution for performance, as you will keep additional, not used View
in memory, but with Visiblity.GONE
it won't be drawn, so won't take much memory and it may be easier to switch visibility rather than removing/adding new View
s