Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android app: Switch images based on theme from code

I am trying to show a favorite button which as two states (pressed/not pressed). I have 2 sets of images I want to use depending up on the theme selected (Light/Dark).

Although i am able to switch the image based on theme I am not sure how to get the Url to the image from the code so that I can show the image according to the button state. I tried using Selectors too, but I don't seem to be able to put ?attr values in selector to switch images by theme.

Style definition:

<attr name="star_on_image" format="reference"/>
<attr name="star_off_image" format="reference"/>

<style name="LightTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="star_on_image">@drawable/ic_action_important</item>
    <item name="star_off_image">@drawable/ic_action_not_important</item>
</style>

<style name="DarkTheme" parent="Theme.AppCompat">
    <item name="star_on_image">@drawable/ic_action_dark_important</item>
    <item name="star_off_image">@drawable/ic_action_dark_not_important</item>
</style>

Button Definition:

<ImageButton
            android:layout_width="@dimen/button_size"
            android:layout_height="@dimen/button_size"
            android:id="@+id/favorite_button_on"
            android:src="?attr/star_off_image"
            android:scaleType="center"
            android:visibility="gone"
            />

I want to switch this image's src attribute to "?attr/star_on_image" from code. Any ideas on how to do this?

like image 701
Nimesh Madhavan Avatar asked May 07 '26 01:05

Nimesh Madhavan


1 Answers

Use this:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.star_on_image, typedValue, true);
ImageButton star = ((ImageButton)findViewById(R.id.favorite_button_on));
star.setImageResource(typedValue.resourceId);
like image 189
ByteHamster Avatar answered May 09 '26 15:05

ByteHamster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!