Reputation: 1653
I can't figure out how to change image resource of ImageButton in code. I have defined following theme in themes.xml:
<resources>
<style name="MMTheme.Blue">
<item name="playButtonImg">@drawable/play_button</item>
<item name="pauseButtonImg">@drawable/pause_button</item>
</style>
</resources>
Attributes are defined in attrs.xml:
<resources>
<attr name="pauseButtonImg" format="integer"/>
<attr name="playButtonImg" format="integer"/>
</resources>
Now I want to change the image resource of ImageButton. I can change it by:
playButton.setImageResource(R.drawable.play_button);
But I want use themes. How to change it using the playByttonImg attribute so I can use different images for different themes ?
Upvotes: 0
Views: 909
Reputation: 1653
Now I have solution for the original question:
public static int getStyledDrawableId(Context context, int attribute)
{
TypedArray a = context.getTheme().obtainStyledAttributes(new int[] { attribute });
int id = a.getResourceId(0, -1);
return id;
}
It returns me a drawable id when I call for example: getStyledDrawableId(getContext(), R.attr.playButtonImg)
. Context HAS TO have the selected theme set.
Attributes should be changed to reference format:
<resources>
<attr name="pauseButtonImg" format="reference"/>
<attr name="playButtonImg" format="reference"/>
</resources>
Upvotes: 4
Reputation: 1653
I still don't know how to access the styles from themes programaticaly, so I had to use a trick with two separate buttons. Each has own style and instead of changing image/style of one button, I am setting the visibility of two styled buttons.
Upvotes: 0